skribe
skribe

Reputation: 3615

How to properly assign new properties to objects in PHP

Ok every once in a while I run into this issue. Say I have a method like the following

10 public function myMethod($someVar){
11    $myObject = new stdClass();
12    $myObject->myProperty = $this->some_model->get_some_data_as_object();
13    $myObject->myProperty->subProperty = $someVar;
14 }

So then it the above function "works" and the sub-property gets assigned but sometimes php throws a warning like below, and other times there is no warning when assigning properties this way to an object.

A PHP Error was encountered
Severity: Warning
Message: Attempt to assign property of non-object
Filename: controllers/MyClass.php
Line Number: 13;

So why does the warning only sometimes occur, and how can this be avoided?

Edit: Please note that I am saying that it "works"! The properties get assigned and a dump shows all the values even the one for subProperty. So the warning is saying it does not like assigning the property but it does it anyway.

Edit: I need to make clarify that subProperty does not exist. i.e. it is not part of the data assigned on line 12. I am both creating the propery and assigning the value on line 13.

Upvotes: 0

Views: 103

Answers (2)

vijaykumar
vijaykumar

Reputation: 4806

That might be problem with this

$this->some_model->get_some_data_as_object() // It's was giving non-object

Added check that if it's a object or not. We can't assign property to non objects

if (is_object($myObject->myProperty->subProperty))
{
    $myObject->myProperty->subProperty = $someVar;
}

Upvotes: 1

Dominique Lorre
Dominique Lorre

Reputation: 1168

$myObject->myProperty is null

You have to check:

if (isset($myObject->myProperty)) {
    $myObject->myProperty->subProperty = $someVar;
}

EDIT: If you want to check that the object is of a certain class you can do:

if (is_a($myObject->myProperty, 'MyPropertyClass')) {
    $myObject->myProperty->subProperty = $someVar;
}

Upvotes: 0

Related Questions