get_object_vars() 与强制转换为数组 [英] get_object_vars() vs. cast to array
问题描述
get_object_vars($obj)
和 (array) $obj
有什么区别吗?
Are there any differences between get_object_vars($obj)
and (array) $obj
?
两者似乎都返回对象的公共属性.
Both seem to return the public properties of the object.
哪个更好?
推荐答案
这并不完全正确.
get_object_vars
是作用域敏感的,将返回所有 visible 属性,除了 static 属性,不管它们的可见性如何.如果你在你的班级之外调用它,你只会得到公共成员;从派生类中,您将获得受保护和公共成员;从类本身中,您将获得所有成员.数组键代表属性名称,不会被破坏.
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.
(array)
转换返回,至少在 PHP 5.3.0 上,所有对象属性,public 和其他.属性的名称根据其保护级别进行了修改:
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
:未损坏,与属性名称相同protected
:属性的键名以*
开头private
:属性的键名以类名开头
public
: not mangled, identical to property namesprotected
: key name for property starts with a*
private
: key name for property starts with the name of the class
参见转换为数组 了解更多信息.
我希望您能够更好地了解哪一种最适合您的情况.
I hope you'll be able to better understand which one is the most appropriate for your situation.
这篇关于get_object_vars() 与强制转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!