PHP Introspection Functions and Example Program

PHP Introspection is the ability of a program to examine an object's characteristics such as its name, parent class (if any), properties and methods.

This makes it possible to write generic debuggers, serializers without knowing the methods and properties, it can discover that information at runtime. .

PHP Introspection Functions and example program

The introspective functions provided by PHP are as follows:

1) class_exists() takes class name as string and returns a boolean value depending on whether that class exists or not.
$existence_status = class_exists(classname);

2) get_declared_classes() function returns an array classes defined, using this array we can check if a particular class exists or not. Example:
$classes = get_declared_classes();

3) get_class_methods() function returns an array of method names defined in class and also which are inherited from superclass.
$methodNames = get_class_methods(classname);

4) get_class_vars() function is similar to get_class_methods() but it returns an associative array in which the keys are the property names in a class and values are their respective values of each property.
$properties = get_class_vars(classname);

5) get_parent_class() function returns the parent class name of class passed as arguments.
$superclassName = get_parent_class(class and);

6) get_object_methods(), get_object_vars() functions are similar to get_class_methods() and get_class_vars() but they require an object as parameter and return the respective methods and properties of an object.

7) is_object() function is used to check if the parameter passed is an object or not, it returns a boolean value.
$object_status = is_object(obj);

8) get_class() function is used to get class corresponding to an object passed as arguments.

PHP Introspection Program Example

Here is the simple php program which demonstrates the use of introspection in php.

class Rectangle
    var $dim1 = 2;
    var $dim2 = 10;
 function Rectangle($dim1,$dim2)
  $this->dim1 = $dim1;
  $this->dim2 = $dim2;
 function area()
  return $this->dim1*$this->dim2;
 function display()
  // any code to display info

$S = new Rectangle(4,2);

//get the class varibale i.e properties
$class_properties = get_class_vars("Rectangle");

//get object properties
$object_properties = get_object_vars($S);

//get class methods
$class_methods = get_class_methods("Rectangle");

//get class corresponding to an object
$object_class = get_class($S);



    [dim1] => 2
    [dim2] => 10
    [dim1] => 4
    [dim2] => 2
    [0] => Rectangle
    [1] => area
    [2] => display