Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

php - get_object_vars() vs. cast to array

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...