R
R
Roman Basharin2016-10-13 00:54:16
PHP
Roman Basharin, 2016-10-13 00:54:16

Creating an object inside another class?

Question 1 - is the following option correct, if not, why not?

class A {
}

class B {
  public $a;

  function __construct() {
    $this->a = new A();
  }
}

2. Even if it's not exactly a true option, it works for me. Question 2. Why is it possible to write an object of another class to a property only through a constructor? It doesn't work like that, but PHP syntax seems to make sense.
class A {
}

class B {
  public $a = new A();
}

upd. It would be very interesting to know the opinion of those who looked at the PHP source code. Maybe this approach really carries hidden logic.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DevMan, 2016-10-13
@Hellek

It doesn't work like that, but PHP syntax seems to make sense.
for
This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

agree or not - it's up to you. in real life it won't change anything.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question