40

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

Both seem to return the public properties of the object.

Which is better?

hakre
  • 193,403
  • 52
  • 435
  • 836
scribu
  • 2,958
  • 4
  • 34
  • 44

3 Answers3

51

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.

tworabbits
  • 1,203
  • 12
  • 17
zneak
  • 134,922
  • 42
  • 253
  • 328
  • 10
    To add, for the `(array)` cast, the `*` for protected and the *classname* for private members will be enclosed in null-bytes (`\x00`), so strictly it's `\x00*\x00` for protected members and likewise for the private members: `\x00className\x00`. Related: **[Array to Object and Object to Array in PHP - interesting behaviour](http://stackoverflow.com/questions/6325447/array-to-object-and-object-to-array-in-php-interesting-behaviour/6325631#6325631)** – hakre Jul 09 '11 at 09:33
  • 2
    Another difference (at least in PHP 5) : with `get_object_vars` the keys will be cast to int if they are numbers, where casting returns string indexes : https://3v4l.org/2Wb9j – Sherbrow Aug 30 '16 at 15:24
  • One more to `(array)` is that it won't include `static` properties either regardless of their visibility. – revo Jul 01 '19 at 07:54
3

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.

d-_-b
  • 21,536
  • 40
  • 150
  • 256
Andre
  • 3,150
  • 23
  • 23
  • 3
    Why should the array cast be less reliable in its behavior than the function? Do you have documentation supporting it? – zneak Mar 24 '10 at 23:50
2

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.

fuxia
  • 62,923
  • 6
  • 54
  • 62