PHP's function to list all objects's attri

2019-01-11 22:22发布

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

5条回答
男人必须洒脱
2楼-- · 2019-01-11 23:02

PHP5 includes a complete Reflection API for going beyond what the older get_class_methods and get_object_vars can do.

查看更多
甜甜的少女心
3楼-- · 2019-01-11 23:16
Reflection::export(new ReflectionObject($Yourobject));
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-11 23:19

You can use the Reflection API's ReflectionClass::getProperties and ReflectionClass::getMethods methods 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_vars and get_class_methods functions. The difference between get_object_vars and get_class_vars is 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.

查看更多
叛逆
5楼-- · 2019-01-11 23:20

You can use get_object_vars to list object variables and get_class_methods to list the methods of a given class.

查看更多
Juvenile、少年°
6楼-- · 2019-01-11 23:20

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));
查看更多
登录 后发表回答