There is such a code

<?php class C { } class B { public function __construct() { return new C(); } } class A extends B { } var_dump(new A()); 

It prints the following: object(A)#1 (0) {} , which means that I get an instance of class A

Is it possible to get an instance of class C this way?

  • php does not have multiple inheritance, but there are traits - Maxim Timakov
  • you create object A, how do you hope to get C? - etki
  • I wonder why you? - korytoff

2 answers 2

You can get the value from the __construct() method by calling it directly. (If parameters are passed to the constructor, then when calling a function, it is also necessary to pass them.)

 class C { } class B { public function __construct() { return new C(); } } class A extends B { } $test = new A(); var_dump($test->__construct()); 

But this is not recommended.

    The task of the constructor is to initialize the initial values ​​of the properties of the object, to perform initialization operations.

    Do not use it to return values, even if there is such a possibility. If you are trying to return something from the constructor, then you are doing something wrong, and you do not need to look for workarounds to do it through the constructor.

    A constructor and a destructor, unlike ordinary methods, should never return a value.