When should I use stdClass and when should I use an array in php oo code?

前端 未结 7 508
太阳男子
太阳男子 2020-11-29 00:33

In the middle of a period of big refactorings at work, I wish to introduce stdClass ***** as a way to return data from functions and I\'m trying to find non-subjectives argu

7条回答
  •  生来不讨喜
    2020-11-29 00:33

    I find stdClass objects over arrays useful when I need to keep my code clean and somewhat sentence-like readable. Take for example function getProperties() which returns a set of properties, say data about a person (name, age, sex). If getProperties() would return an associative array, when you want to use one of the returned properties, you would write two instructions:

    $data = getProperties();
    echo $data['name'];
    

    On the other hand, if getProperties() returns a stdClass then you could write that in just one instruction:

    echo getProperties()->name;
    

提交回复
热议问题