It seems quite simple but I’m not getting it done for quite a while now…
class Main
{
public $sub1;
public $sub2;
public function __construct()
{
$this->sub1 = new Sub1();
$this->sub2 = new Sub2();
}
}
class Sub1 extends Main
{
public function __construct() {}
public function helloWorld()
{
echo "hello world";
}
}
class Sub2 extends Main
{
public function __construct()
{
$this->sub1->helloWorld();
}
}
new Main();
The result of the code is Fatal error: Call to a member function helloWorld(). But why? I don’t understand why the sub1 property of the Main class is NULL when I try to access it from sub2. Could anyone please explain it to me? Am I doing something basically wrong in terms of OOP programming? Am I hurting any concepts? Are there any better solutions?
Best regards!
You are overriding Main’s
__construct()in both Sub1 and Sub2, meaning Main’s construct is never called. Even if you were to callparent::__construct()in Sub1 and Sub2’s construct, you would get an infinite loop because Main’s construct is initializing both subs.Edit: Since you want to share objects, here are a couple SO questions that can help:
Sharing objects between PHP classes
How to create an object in a parent class shared by its children classes?