M
M
Max Ba2018-12-25 15:37:53
PHP
Max Ba, 2018-12-25 15:37:53

How to correctly initialize an object in an object?

Guys, tell me. It is necessary in the first class, to assign to the $this->a property an array from the outer class (Test2).

class Test{
  protected $a = array();

  public function __construct(){
    $tmp = new Test2();
    $this->a = $tmp->get();
  }
}

class Test2{
  private $data = array();

  public function __construct(){
    $this->data = range(1,100);
  }

  public function get(){
    return $this->data;
  }
}

Am I right in this example?
Now you need to call one class like this, inside another.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Shamanov, 2018-12-25
@SilenceOfWinter

read about Dependency Injection

D
Danila, 2018-12-25
Ridzhi @Ridzhi

https://ideone.com/S4VJFU
Should work in 5.4+

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question