get_object_vars() vs. cast to array

前端 未结 3 994
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 09:41

Are there any differences between get_object_vars($obj) and (array) $obj ?

Both seem to return the public properties of the object.

相关标签:
3条回答
  • 2020-12-08 10:11

    The get_object_vars() function is a clearer method of achieving the effect you want. Although casting it to an array is a solution as well, this behavior might change in later versions of PHP.

    I don't know if there is an actual difference between the two methods but the arguments above would lead me to use the function.

    0 讨论(0)
  • 2020-12-08 10:21

    Better is what is what you actually need. get_object_vars() doesn’t show private and protected members. See this comment in the manual for an example.

    0 讨论(0)
  • 2020-12-08 10:22

    This is not exactly true.

    get_object_vars is scope-sensitive and will return all visible properties excepting static properties regardless of their visbility. If you call it from outside your class, you'll only get the public members; from a derived class, you'll get the protected and public members; and from the class itself, you'll get all the members. The array keys represent the property names, and are not mangled.

    The (array) cast returns, at least on PHP 5.3.0, all the object properties, public and otherwise. The name of the properties are mangled according to their protection level:

    • public: not mangled, identical to property names
    • protected: key name for property starts with a *
    • private: key name for property starts with the name of the class

    See casting to an array for more informations.

    I hope you'll be able to better understand which one is the most appropriate for your situation.

    0 讨论(0)
提交回复
热议问题