get_object_vars()vs. cast to array [英] get_object_vars() vs. cast to array

查看:132
本文介绍了get_object_vars()vs. cast to array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

get_object_vars($ obj)(array)$ obj

两者似乎都返回对象的公共属性。



这更好吗?



get_object_vars 是范围敏感的,并且除了 static 属性,将返回所有可见属性,而不考虑其可见性。如果你从课堂外面打电话,你只能得到公共会员;从派生类,你会得到受保护的和公共的成员;并从类本身,你会得到所有的成员。



(array) cast返回,至少在PHP 5.3.0上,所有对象属性,public和其他。根据其保护级别对属性名称进行修改:




  • public :未损坏,与属性名称相同

  • protected :属性的键名称以 *

  • private :属性的键名称以类名
  • 开头


请参阅

我希望你能更好地理解哪一个是最合适的您的情况。


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?

解决方案

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.

这篇关于get_object_vars()vs. cast to array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆