1

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";
3
  • What happens if you give your class A a constructor? Also, protected properties can't be set from outside the class IIRC. Commented Feb 18, 2017 at 19:26
  • 1
    Hello Mike. Constructor in class A executes ok, but using $varA="test"; in that constructor is pointless, it gets forgotten. If I use $this->varA="test"; as suggested by Gergely below then it works fine... provided I change that protected property to 'public' like you said. Should have spotted that the $varA would only be scoped to the constructor function, but sometimes you can't see the wood for looking. Thanks for the help. Commented Feb 18, 2017 at 20:26
  • Yeah, I didn't notice the missing $this Commented Feb 18, 2017 at 20:29

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Gergely, spot on.
By the way, miken32 is correct, the $varA in class A needs to be public. Thanks for the help chaps. this one has had me gnawing my arm off!
Not nessesarily. Sometimes you want to hide some of the properties from other classes. To access these variables in a coordinated way, you can extend your class with getter/setter methods. But yeah, to make $obj->varB->varA = "Whatever"; work, it needs to be public.
Yep, I'm using getters and setters. My error came from trying to simplify the problem to post on here - the original code is horrendous to wade through.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.