Robbie
Robbie

Reputation: 23

PHP - passing values to nested objects - Warning: Creating default object from empty value

I'm new to PHP OOP, and understand that "Warning: Creating default object from empty value" comes from an object not being initialised before writing, but I'm struggling to understand why I'm getting the error with the following code.

Please help!

class A { public $varA; }

class B {
    public $varB;
    function __construct(){ $varB = new A; }
}

$obj = new B;
$obj->varB->varA = "Whatever";

Upvotes: 1

Views: 125

Answers (1)

Gergely Lukacsy
Gergely Lukacsy

Reputation: 3074

When you create an instance of an object, you should use the pseudo variable "$this" to address the property of the object.

In your code, $varB in the 5th row doesn't addresses the class property, instead it is just a local variable, which gets destroyed right after the function completes (since it looses all references to it). Read more about this behavior in the "variable scopes" manual page.

So your code should look like this:

class A { public $varA; }

class B {
    public $varB;
    function __construct(){ $this->varB = new A(); }
}

$obj = new B();
$obj->varB->varA = "Whatever";
var_dump($obj);

Upvotes: 3

Related Questions