Sunday 21 October 2012

Introspection in PHP

Introspection is the ability of a program to examine an object's characteristics, such as its name, parent class (if Exist), properties, and methods. With introspection, you can write code that operates on any class or object. You don't need to know which methods or properties are defined when you write your code; instead, you can discover that information at runtime, which makes it possible for you to write generic debuggers, serializers, profilers, etc. In this section, we look at the introspective functions provided by PHP.

It have mainly two parts

Examining Classes
Examining an Object




Examining Classes

To determine whether a class exists or not.

Function used for that
1)      class_exists( )
2)      get_declared_classes( )


Syntax:

Boolean class exists(String classname)

      Returns that the class with the name exits or not.

Array get_declared_classes( )
       
        Returns the declare classes in the current page or belongs to the current page.




Examining an Object

Functions for the examing object
1)      method_exists();

Syntax
            Boolean method_exists(object obj, String method_name);

Check whether the method name dedined  in the method is exist in the given class object.

2) get_parent_class( )

Syntax
                                         
            String  get_parent_class( Object obj)

Returns the parent class of the object variable is exist.

3) get_class_methods()

Array get_class_methods(string class name)

Returns the all methods that are defines in the class

4)  get_class_vars()

Syntax
Array get_class_vars( String Class name)

Returns the Class variables .




To check the object and its method just followa the steps:

1) Determing where the variable is object or not: With method  isobject(var)

2) Find that is have any parent class or not with the help of the method get_parent_class(Object)

3) Then get the methods and the variables of the class from the methos
get_class_methods(string class name)
get_class_vars( String Class name)

4) Display it on the screen

No comments:

Post a Comment