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.
Example:
$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.
Example:
$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.
Example:
$properties = get_class_vars(classname);

5) get_parent_class() function returns the parent class name of class passed as arguments.
Example:
$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.
Example:
$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.
<?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);

print_r($class_properties);
print_r($object_properties);
print_r($class_methods);
print_r($object_class);
?>

Output

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