Alex
Alex

Reputation: 44709

PHP's function to list all objects's properties and methods

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

Upvotes: 27

Views: 42212

Answers (5)

Toinou Wbr
Toinou Wbr

Reputation: 96

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));

Upvotes: 0

Candidasa
Candidasa

Reputation: 8710

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.

Upvotes: 15

Anti Veeranna
Anti Veeranna

Reputation: 11583

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

Upvotes: 11

Paul Dixon
Paul Dixon

Reputation: 300825

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

Upvotes: 19

Vlad Andersen
Vlad Andersen

Reputation: 366

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

Upvotes: 8

Related Questions