php get_object_vars() 与强制转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2512212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:46:11  来源:igfitidea点击:

get_object_vars() vs. cast to array

phparraysobjectcastingproperties

提问by scribu

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

get_object_vars($obj)和之间有什么区别(array) $obj吗?

Both seem to return the public properties of the object.

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

Which is better?

哪个更好?

回答by zneak

This is not exactly true.

这并不完全正确。

get_object_varsis scope-sensitive and will return all visibleproperties excepting staticproperties 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.

get_object_vars是范围敏感的,将返回除静态属性之外的所有可见属性,而不管它们的可见性。如果你在你的班级之外调用它,你只会得到公共成员;从派生类中,您将获得受保护和公共成员;从类本身中,您将获得所有成员。数组键代表属性名称,不会被破坏。

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:

(array)投的回报,至少在PHP 5.3.0,所有的对象属性,公众和其他。属性的名称根据其保护级别进行了修改:

  • 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
  • public: 未损坏,与属性名称相同
  • protected: 属性的键名以 a 开头 *
  • private: 属性的键名以类名开头

See casting to an arrayfor more informations.

有关更多信息,请参阅强制转换为数组

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

我希望您能够更好地了解哪一种最适合您的情况。

回答by Andre

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.

get_object_vars()功能是实现你想要的效果更清晰的方法。尽管将其转换为数组也是一种解决方案,但这种行为可能会在 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.

我不知道这两种方法之间是否存在实际差异,但上面的参数会引导我使用该函数。

回答by fuxia

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

更好的是你真正需要的东西。get_object_vars() 不显示私有成员和受保护成员。有关示例,请参阅手册中的此注释