Get Functions And Variables Of An Object With PHP

16th April 2008

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
  2. {
  3.  
  4. public $publicVariable = 'value1';
  5. private $privateVariable = 'value2';
  6.  
  7. public function testClass()
  8. {
  9. }
  10.  
  11. public function aPublicFunction()
  12. {
  13. }
  14.  
  15. private function aPrivateFunction()
  16. {
  17. }
  18. }

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>';
  7.  
  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 = '';
  3. foreach(get_object_vars($obj) as $key=>$var){
  4. $output .= ''.$key.' '.$var.'';
  5. }
  6. $output .= '';
  7.  
  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.