douchuoliu4422 2016-09-29 08:54
浏览 86

如何在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.

  • 写回答

2条回答 默认 最新

  • douwen5690 2016-09-29 08:57
    关注

    $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;
    }
    
    评论

报告相同问题?