PHP:对象上的array_map?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/114229/
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
PHP: array_map on object?
提问by Christian Davén
I'm trying to write a function that formats every (string) member/variable in an object, for example with a callback function. The variable names are unknown to me, so it must work with objects of all classes.
我正在尝试编写一个函数来格式化对象中的每个(字符串)成员/变量,例如使用回调函数。我不知道变量名,所以它必须适用于所有类的对象。
How can I achieve something similar to array_mapor array_walkwith objects?
我怎样才能实现类似于array_map或array_walk使用对象的东西?
回答by Sietse
use get_object_vars()to get an associative array of the members, and use the functions you mentioned.
使用get_object_vars()获取成员的关联数组,并使用您提到的函数。
btw, you can also do a foreach on an object like you would on an array, which is sometimes useful as well.
顺便说一句,您也可以像在数组上一样对对象执行 foreach,这有时也很有用。
回答by tpk
You can use get_object_vars(), but if you need more control, try using reflection. It's slower than get_object_vars()(or get_class_methods()for that matter), but it's much more powerful.
您可以使用get_object_vars(),但如果您需要更多控制,请尝试使用反射。它比get_object_vars()(或get_class_methods()就此而言)慢,但它更强大。
回答by Grey Panther
You are looking for get_object_vars/ get_class_methods(the first gets the variables, the second the method names).
您正在寻找get_object_vars/ get_class_methods(第一个获取变量,第二个获取方法名称)。

