You have a slight misunderstanding about how inheritance works. I think because of this line in constructor B:
A_Factory::create_A();
A parent is not a property of a child class. If you create new A([...]) inside constructor B, it will be another class completely separate from your B, and there is no way to βmergeβ it with an existing object. To build a parent from a child class, you must do this:
class B { function __construct() { parent:__construct(new X(),new Y(),new Z()); } }
Here is a way to create your classes using factory and some hint type. Notice how I moved the different new XYZ() so that they are not in your class constructors. Naked news in designers is considered bad practice, as they hide the dependencies of your classes.
class B_Factory { public static function create_B(X $X,Y $Y, Z $Z) { return new B($X, $Y, $Z); } } class X {} class Y {} class Z {} class A { public function __construct(X $X, Y $Y, Z $Z) { $this->foo = "foo"; } } class B extends A { public function __construct(X $X, Y $Y, Z $Z) { parent::__construct($X,$Y,$Z); } } $B = B_Factory::create_B(new X(), new Y(), new Z()); var_dump($B->foo);
The real answer is : you want your factory to be a container for dependency injection like Auryn , and using type hints your classes will be recursively created with their dependencies using reflection .
in your case (adapted from the example in auryn github repo):
class X {} class Y {} class Z {} class A { public function __construct(X $X, Y $Y, Z $Z) { $this->foo = "foo"; } } class B extends A { public function __construct(X $X, Y $Y, Z $Z) { parent::__construct($X, $Y, $Z); } } $injector = new Auryn\Injector; $B = $injector->make('B'); var_dump($B->foo);
Using reflection, Auryn can recursively understand what components your classes need, instantiate them, and pass them to class constructors.