B
B
BUKUBAKA2016-09-05 21:12:34
PHP
BUKUBAKA, 2016-09-05 21:12:34

Friends, how to change the value of the $b property (add one) for each object of class T specified in the constructor of class G?

class G{
  var $a;
  public function __construct(){
    $massiv=[];
    for ($i=0;$i<4;$i=$i+1){
      ${'fu'.$i} = new T;
      ${'fu'.$i}->b=rand(0,1000);
      $massiv[]=${'tree'.$i};
      }
   }
}

class T{
  var $b;	 
  var $s; 
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2016-09-05
Protko @Fesor

1) var - don't use this keyword. Use public. Better yet, private.
2) encapsulation, the law of demeter. Don't change the state of objects directly. Use messages (method calls).
3) these pandemoniums with the dynamic creation of variable names are meaningless
4) the names of classes, properties, methods, and in general should be meaningful. You should be able to, I don't know, read the code out loud! and to make it clear to everyone around.

class T{
    private $b;
    private $s;

    public function __construct() 
    {
         $this->b = mt_rand(0, 1000);
         $this->s = 'foo';
    }
}

class G
{
    public function __construct(array $t) 
    {
          // ...
    }
}

$g = new G(array_map(function () {
    return new T();
}, range(1, 4));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question