Get Functions And Variables Of An Object With PHP

16th April 2008 - 2 minutes read time

It is possible to find out what functions and variables are available from an object at runtime using the PHP functions get_class_methods() and get_object_vars().

Take the following class called testClass.

  1. class testClass {
  3. public $publicVariable = 'value1';
  4. private $privateVariable = 'value2';
  6. public function testClass()
  7. {
  8. }
  10. public function aPublicFunction()
  11. {
  12. }
  14. private function aPrivateFunction()
  15. {
  16. }
  17. }

To find out the functions available from the class you can use the function get_class_methods(). This takes either a class name as a string or an instance of the object. The following bit of code will print out all of the functions in the class.

  1. $obj = new testClass();
  2. $output = '<ol>';
  3. foreach(get_class_methods($obj) as $function){
  4. $output .= '<li>'.$function.'</li>';
  5. }
  6. $output .= '</ol>';
  8. echo $output;

This will print out the following.

  1. testClass
  2. aPublicFunction

The function will only give the the publicly available functions from the class or object and not just a list of all functions available.

To print off the variables for an object you can use the get_object_vars() function, the parameter here is an instance of the object you want to test. Another function called get_class_vars() is available if you want to use the class name, rather than instantiate an object before testing. The following code will print off all variables from the an object created from the class testClass.

  1. $obj = new testClass();
  2. $output = '<ol>';
  3. foreach(get_object_vars($obj) as $key=>$var){
  4. $output .= '<li>'.$key.' '.$var.'</li>';
  5. }
  6. $output .= '</ol>';
  8. echo $output;

This will print out the following.

  1. publicVariable value1

The key is the variable name and the value is the value of that variable. The function will only give you information on public variables.

It is possible to get all functions and variables from a class or object, but you must use the PHP Reflection API in order to do this.

Add new comment

The content of this field is kept private and will not be shown publicly.