Related Links : Search Engine Optimization | | Search Engine Marketing | Online Marketing | Freelance Programmer| SEO Thailand | SEO Expert | SEO services | PHP Programmer Thailand | SEO Tutorial | What is SEO |

  Home Our SEO Services SEO Expert Consultant Php Programmer Keyword Suggestion Scripts|Articles| Email : sachin {at} jainsachin {dot} com

PHP | Reflection | Manual | Tutorial | Help

SEO Services



Website Programming in PHP / MYSQL



SEO Tools




    Friends


      Reflection

      Reflection

      Introduction

      PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions and methods as well as extensions. Additionally, the reflection API also offers ways of retrieving doc comments for functions, classes and methods.

      The reflection API is an object-oriented extension to the Zend Engine, consisting of the following classes:

      <?php
      class Reflection { }
      interface 
      Reflector { }
      class 
      ReflectionException extends Exception { }
      class 
      ReflectionFunction extends ReflectionFunctionAbstract implements Reflector { }
      class 
      ReflectionParameter implements Reflector { }
      class 
      ReflectionMethod extends ReflectionFunctionAbstract implements Reflector { }
      class 
      ReflectionClass implements Reflector { }
      class 
      ReflectionObject extends ReflectionClass { }
      class 
      ReflectionProperty implements Reflector { }
      class 
      ReflectionExtension implements Reflector { }
      ?>

      Note: For details on these classes, have a look at the next chapters.

      If we were to execute the code in the example below:

      Example #1 Basic usage of the reflection API

      <?php
      Reflection
      ::export(new ReflectionClass('Exception'));
      ?>

      The above example will output:

      Class [ <internal> class Exception ] {
      
        - Constants [0] {
        }
      
        - Static properties [0] {
        }
      
        - Static methods [0] {
        }
      
        - Properties [6] {
          Property [ <default> protected $message ]
          Property [ <default> private $string ]
          Property [ <default> protected $code ]
          Property [ <default> protected $file ]
          Property [ <default> protected $line ]
          Property [ <default> private $trace ]
        }
      
        - Methods [9] {
          Method [ <internal> final private method __clone ] {
          }
      
          Method [ <internal, ctor> public method __construct ] {
      
            - Parameters [2] {
              Parameter #0 [ <optional> $message ]
              Parameter #1 [ <optional> $code ]
            }
          }
      
          Method [ <internal> final public method getMessage ] {
          }
      
          Method [ <internal> final public method getCode ] {
          }
      
          Method [ <internal> final public method getFile ] {
          }
      
          Method [ <internal> final public method getLine ] {
          }
      
          Method [ <internal> final public method getTrace ] {
          }
      
          Method [ <internal> final public method getTraceAsString ] {
          }
      
          Method [ <internal> public method __toString ] {
          }
        }
      }
      

      Reflector

      Reflector is an interface implemented by all exportable Reflection classes.

      <?php
      interface Reflector
      {
          public 
      string __toString()
          public static 
      string export()
      }
      ?>

      ReflectionException

      ReflectionException extends the standard Exception and is thrown by Reflection API. No specific methods or properties are introduced.

      ReflectionFunction

      The ReflectionFunction class lets you reverse-engineer functions.

      <?php
      class ReflectionFunction extends ReflectionFunctionAbstract implements Reflector
      {
          final private 
      __clone()
          public 
      void __construct(string name)
          public 
      string __toString()
          public static 
      string export(string namebool return)
          public 
      string getName()
          public 
      bool isInternal()
          public 
      bool isDisabled()
          public 
      bool isUserDefined()
          public 
      string getFileName()
          public 
      int getStartLine()
          public 
      int getEndLine()
          public 
      string getDocComment()
          public array 
      getStaticVariables()
          public 
      mixed invoke([mixed args [, ...]])
          public 
      mixed invokeArgs(array args)
          public 
      bool returnsReference()
          public 
      ReflectionParameter[] getParameters()
          public 
      int getNumberOfParameters()
          public 
      int getNumberOfRequiredParameters()
      }
      ?>

      Parent class ReflectionFunctionAbstract has the same methods except invoke(), invokeArgs(), export() and isDisabled().

      Note: getNumberOfParameters() and getNumberOfRequiredParameters() were added in PHP 5.0.3, while invokeArgs() was added in PHP 5.1.0.

      To introspect a function, you will first have to create an instance of the ReflectionFunction class. You can then call any of the above methods on this instance.

      Example #2 Using the ReflectionFunction class

      <?php
      /**
       * A simple counter
       *
       * @return    int
       */
      function counter() 
      {
          static 
      $c 0;
          return 
      $c++;
      }

      // Create an instance of the ReflectionFunction class
      $func = new ReflectionFunction('counter');

      // Print out basic information
      printf(
          
      "===> The %s function '%s'\n".
          
      "     declared in %s\n".
          
      "     lines %d to %d\n",
          
      $func->isInternal() ? 'internal' 'user-defined',
          
      $func->getName(),
          
      $func->getFileName(),
          
      $func->getStartLine(),
          
      $func->getEndline()
      );

      // Print documentation comment
      printf("---> Documentation:\n %s\n"var_export($func->getDocComment(), 1));

      // Print static variables if existant
      if ($statics $func->getStaticVariables())
      {
          
      printf("---> Static variables: %s\n"var_export($statics1));
      }

      // Invoke the function
      printf("---> Invokation results in: ");
      var_dump($func->invoke());


      // you may prefer to use the export() method
      echo "\nReflectionFunction::export() results:\n";
      echo 
      ReflectionFunction::export('counter');
      ?>

      Note: The method invoke() accepts a variable number of arguments which are passed to the function just as in call_user_func().

      ReflectionParameter

      The ReflectionParameter class retrieves information about a function's or method's parameters.

      <?php
      class ReflectionParameter implements Reflector
      {
          final private 
      __clone()
          public 
      void __construct(string function, string parameter)
          public 
      string __toString()
          public static 
      string export(mixed function, mixed parameterbool return)
          public 
      string getName()
          public 
      bool isPassedByReference()
          public 
      ReflectionClass getDeclaringClass()
          public 
      ReflectionClass getClass()
          public 
      bool isArray()
          public 
      bool allowsNull()
          public 
      bool isPassedByReference()
          public 
      bool isOptional()
          public 
      bool isDefaultValueAvailable()
          public 
      mixed getDefaultValue()
      }
      ?>

      Note: getDefaultValue(), isDefaultValueAvailable() and isOptional() were added in PHP 5.0.3, while isArray() was added in PHP 5.1.0. getDeclaringFunction() and getPosition() were added in PHP 5.2.3.

      To introspect function parameters, you will first have to create an instance of the ReflectionFunction or ReflectionMethod classes and then use their getParameters() method to retrieve an array of parameters.

      Example #3 Using the ReflectionParameter class

      <?php
      function foo($a$b$c) { }
      function 
      bar(Exception $a, &$b$c) { }
      function 
      baz(ReflectionFunction $a$b 1$c null) { }
      function 
      abc() { }

      // Create an instance of ReflectionFunction with the
      // parameter given from the command line.    
      $reflect = new ReflectionFunction($argv[1]);

      echo 
      $reflect;

      foreach (
      $reflect->getParameters() as $i => $param) {
          
      printf(
              
      "-- Parameter #%d: %s {\n".
              
      "   Class: %s\n".
              
      "   Allows NULL: %s\n".
              
      "   Passed to by reference: %s\n".
              
      "   Is optional?: %s\n".
              
      "}\n",
              
      $i
              
      $param->getName(),
              
      var_export($param->getClass(), 1),
              
      var_export($param->allowsNull(), 1),
              
      var_export($param->isPassedByReference(), 1),
              
      $param->isOptional() ? 'yes' 'no'
          
      );
      }
      ?>

      ReflectionClass

      The ReflectionClass class lets you reverse-engineer classes and interfaces.

      <?php
      class ReflectionClass implements Reflector
      {
          final private 
      __clone()
          public 
      void __construct(string name)
          public 
      string __toString()
          public static 
      string export(mixed class, bool return)
          public 
      string getName()
          public 
      bool isInternal()
          public 
      bool isUserDefined()
          public 
      bool isInstantiable()
          public 
      bool hasConstant(string name)
          public 
      bool hasMethod(string name)
          public 
      bool hasProperty(string name)
          public 
      string getFileName()
          public 
      int getStartLine()
          public 
      int getEndLine()
          public 
      string getDocComment()
          public 
      ReflectionMethod getConstructor()
          public 
      ReflectionMethod getMethod(string name)
          public 
      ReflectionMethod[] getMethods()
          public 
      ReflectionProperty getProperty(string name)
          public 
      ReflectionProperty[] getProperties()
          public array 
      getConstants()
          public 
      mixed getConstant(string name)
          public 
      ReflectionClass[] getInterfaces()
          public 
      bool isInterface()
          public 
      bool isAbstract()
          public 
      bool isFinal()
          public 
      int getModifiers()
          public 
      bool isInstance(stdclass object)
          public 
      stdclass newInstance(mixed args)
          public 
      stdclass newInstanceArgs(array args)
          public 
      ReflectionClass getParentClass()
          public 
      bool isSubclassOf(ReflectionClass class)
          public array 
      getStaticProperties()
          public 
      mixed getStaticPropertyValue(string name [, mixed default])
          public 
      void setStaticPropertyValue(string namemixed value)
          public array 
      getDefaultProperties()
          public 
      bool isIterateable()
          public 
      bool implementsInterface(string name)
          public 
      ReflectionExtension getExtension()
          public 
      string getExtensionName()
      }
      ?>

      Note: hasConstant(), hasMethod(), hasProperty(), getStaticPropertyValue() and setStaticPropertyValue() were added in PHP 5.1.0, while newInstanceArgs() was added in PHP 5.1.3.

      To introspect a class, you will first have to create an instance of the ReflectionClass class. You can then call any of the above methods on this instance.

      Example #4 Using the ReflectionClass class

      <?php
      interface Serializable
      {
          
      // ...
      }

      class 
      Object
      {
          
      // ...
      }

      /**
       * A counter class
       */
      class Counter extends Object implements Serializable 
      {
          const 
      START 0;
          private static 
      $c Counter::START;

          
      /**
           * Invoke counter
           *
           * @access  public
           * @return  int
           */
          
      public function count() {
              return 
      self::$c++;
          }
      }

      // Create an instance of the ReflectionClass class
      $class = new ReflectionClass('Counter');

      // Print out basic information
      printf(
          
      "===> The %s%s%s %s '%s' [extends %s]\n" .
          
      "     declared in %s\n" .
          
      "     lines %d to %d\n" .
          
      "     having the modifiers %d [%s]\n",
              
      $class->isInternal() ? 'internal' 'user-defined',
              
      $class->isAbstract() ? ' abstract' '',
              
      $class->isFinal() ? ' final' '',
              
      $class->isInterface() ? 'interface' 'class',
              
      $class->getName(),
              
      var_export($class->getParentClass(), 1),
              
      $class->getFileName(),
              
      $class->getStartLine(),
              
      $class->getEndline(),
              
      $class->getModifiers(),
              
      implode(' 'Reflection::getModifierNames($class->getModifiers()))
      );

      // Print documentation comment
      printf("---> Documentation:\n %s\n"var_export($class->getDocComment(), 1));

      // Print which interfaces are implemented by this class
      printf("---> Implements:\n %s\n"var_export($class->getInterfaces(), 1));

      // Print class constants
      printf("---> Constants: %s\n"var_export($class->getConstants(), 1));

      // Print class properties
      printf("---> Properties: %s\n"var_export($class->getProperties(), 1));

      // Print class methods
      printf("---> Methods: %s\n"var_export($class->getMethods(), 1));

      // If this class is instantiable, create an instance
      if ($class->isInstantiable()) {
          
      $counter $class->newInstance();

          echo 
      '---> $counter is instance? '
          echo 
      $class->isInstance($counter) ? 'yes' 'no';

          echo 
      "\n---> new Object() is instance? ";
          echo 
      $class->isInstance(new Object()) ? 'yes' 'no';
      }
      ?>

      Note: The method newInstance() accepts a variable number of arguments which are passed to the function just as in call_user_func().

      Note: $class = new ReflectionClass('Foo'); $class->isInstance($arg) is equivalent to $arg instanceof Foo or is_a($arg, 'Foo').

      ReflectionObject

      The ReflectionObject class lets you reverse-engineer objects.

      <?php
      class ReflectionObject extends ReflectionClass
      {
          final private 
      __clone()
          public 
      void __construct(mixed object)
          public 
      string __toString()
          public static 
      string export(mixed objectbool return)
      }
      ?>

      ReflectionMethod

      The ReflectionMethod class lets you reverse-engineer class methods.

      <?php
      class ReflectionMethod extends ReflectionFunctionAbstract implements Reflector
      {
          public 
      void __construct(mixed class, string name)
          public 
      string __toString()
          public static 
      string export(mixed class, string namebool return)
          public 
      mixed invoke(stdclass object [, mixed args [, ...]])
          public 
      mixed invokeArgs(stdclass object, array args)
          public 
      bool isFinal()
          public 
      bool isAbstract()
          public 
      bool isPublic()
          public 
      bool isPrivate()
          public 
      bool isProtected()
          public 
      bool isStatic()
          public 
      bool isConstructor()
          public 
      bool isDestructor()
          public 
      int getModifiers()
          public 
      ReflectionClass getDeclaringClass()

          
      // Inherited from ReflectionFunctionAbstract
          
      final private __clone()
          public 
      string getName()
          public 
      bool isInternal()
          public 
      bool isUserDefined()
          public 
      string getFileName()
          public 
      int getStartLine()
          public 
      int getEndLine()
          public 
      string getDocComment()
          public array 
      getStaticVariables()
          public 
      bool returnsReference()
          public 
      ReflectionParameter[] getParameters()
          public 
      int getNumberOfParameters()
          public 
      int getNumberOfRequiredParameters()
      }
      ?>

      To introspect a method, you will first have to create an instance of the ReflectionMethod class. You can then call any of the above methods on this instance.

      Example #5 Using the ReflectionMethod class

      <?php
      class Counter
      {
          private static 
      $c 0;

          
      /**
           * Increment counter
           *
           * @final
           * @static
           * @access  public
           * @return  int
           */
          
      final public static function increment()
          {
              return ++
      self::$c;
          }
      }

      // Create an instance of the ReflectionMethod class
      $method = new ReflectionMethod('Counter''increment');

      // Print out basic information
      printf(
          
      "===> The %s%s%s%s%s%s%s method '%s' (which is %s)\n" .
          
      "     declared in %s\n" .
          
      "     lines %d to %d\n" .
          
      "     having the modifiers %d[%s]\n",
              
      $method->isInternal() ? 'internal' 'user-defined',
              
      $method->isAbstract() ? ' abstract' '',
              
      $method->isFinal() ? ' final' '',
              
      $method->isPublic() ? ' public' '',
              
      $method->isPrivate

      SEO by Jainsachin