Get Functions And Variables Of An Object With PHP

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.

class testClass {
 
 public $publicVariable = 'value1';
 private $privateVariable = 'value2';
 
 public function testClass()
 {
 }
 	
 public function aPublicFunction()
 {
 }
 	
 private function aPrivateFunction()
 {
 }
}

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.

$obj = new testClass();
$output = '<ol>';
foreach(get_class_methods($obj) as $function){
 $output .= '<li>'.$function.'</li>';			
}
$output .= '</ol>';
 
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.

$obj = new testClass();
$output = '<ol>';
foreach(get_object_vars($obj) as $key=>$var){
 $output .= '<li>'.$key.' '.$var.'</li>';			
}
$output .= '</ol>';
 
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.
CAPTCHA
1 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.