PHP 列出所有对象属性的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1372127/
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 02:14:47  来源:igfitidea点击:

PHP's function to list all objects's attributes

phpattributes

提问by Alex

Is there a function to list all object's attributes (like public methods and properties) in PHP similar to Python's dir()?

是否有一个函数可以在 PHP 中列出类似于 Python 的所有对象的属性(如公共方法和属性)dir()

回答by Paul Dixon

PHP5 includes a complete Reflection APIfor going beyond what the older get_class_methodsand get_object_varscan do.

PHP5 包含一个完整的反射 API,用于超越旧的get_class_methodsget_object_vars可以做的事情。

回答by Candidasa

You can use the Reflection API's ReflectionClass::getPropertiesand ReflectionClass::getMethodsmethods to do this (although the API doesn't seem to be very well documented). Note that PHP reflection only reflects compile time information, not runtime objects. If you want runtime objects to also be included in your query results, best to use the get_object_vars, get_class_varsand get_class_methodsfunctions. The difference between get_object_varsand get_class_varsis that the former gets you all the variables on a given object (including those dynamically added at runtime), while the latter gives you only those which have been explicitly declared in the class.

您可以使用反射 APIReflectionClass::getPropertiesReflectionClass::getMethods方法来执行此操作(尽管 API 似乎没有很好的文档记录)。请注意,PHP 反射仅反映编译时信息,而不反映运行时对象。如果您希望运行时对象也包含在查询结果中,最好使用get_object_vars,get_class_varsget_class_methods函数。get_object_vars和之间的区别在于,get_class_vars前者为您提供给定对象上的所有变量(包括在运行时动态添加的变量),而后者仅提供已在类中明确声明的那些。

回答by Anti Veeranna

Reflection::export(new ReflectionObject($Yourobject));

回答by Vlad Andersen

You can use get_object_varsto list object variables and get_class_methodsto list the methods of a given class.

您可以使用get_object_vars来列出对象变量并get_class_methods列出给定类的方法。

回答by Toinou Wbr

If you want to go deeper, and also get the private var of the object, you can use closure for that. like:

如果你想更深入,并获得对象的私有变量,你可以使用闭包。喜欢:

$sweetsThief = function ($obj) {
  return get_object_vars($obj);
};

$sweetsThief = \Closure::bind($sweetsThief, null, $myobj);

var_dump($sweetsThief($myobj));