【发布时间】:2009-09-03 08:27:19
【问题描述】:
有没有类似于 Python 的dir() 的 PHP 中列出所有对象的公共方法和属性的函数?
【问题讨论】:
有没有类似于 Python 的dir() 的 PHP 中列出所有对象的公共方法和属性的函数?
【问题讨论】:
您可以使用get_object_vars 列出对象变量,使用get_class_methods 列出给定类的方法。
【讨论】:
PHP5 包含一个完整的Reflection API,以超越旧的get_class_methods 和get_object_vars 的功能。
【讨论】:
您可以使用反射 API 的 ReflectionClass::getProperties 和 ReflectionClass::getMethods 方法来执行此操作(尽管 API 似乎没有很好的文档记录)。请注意,PHP 反射仅反映编译时信息,而不是运行时对象。如果您希望运行时对象也包含在查询结果中,最好使用get_object_vars、get_class_vars 和get_class_methods 函数。 get_object_vars 和 get_class_vars 之间的区别在于,前者获取给定对象上的所有变量(包括在运行时动态添加的变量),而后者仅提供已在类中显式声明的变量。
【讨论】:
Reflection::export(new ReflectionObject($Yourobject));
【讨论】:
如果你想更深入,也想得到对象的私有变量,你可以使用闭包。喜欢:
$sweetsThief = function ($obj) {
return get_object_vars($obj);
};
$sweetsThief = \Closure::bind($sweetsThief, null, $myobj);
var_dump($sweetsThief($myobj));
【讨论】: