ReflectionFunction

The ReflectionFunction class lets you reverse-engineer functions.

<?php
  class ReflectionFunction implements Reflector {
      public __construct(string name)
      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 mixed invoke(mixed* args)
      public string toString()
      public bool returnsReference()
      public ReflectionParameter[] getParameters()
  }
?>

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 14-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($statics, 1));
  }

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

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