Dedicated servers
& web hosting directory

   
Quick Hosting Links
Apollohosting.com, Lunarpages.com, GalaxyVisions.com, Razorservers, WhosBehindYourWebsite, BeeWhois.com 
Good and Honest Host of the month, August 2008, WSServers.com
Advance Search   Dedicated Servers   Company Name   HostMatch
Thank you for visiting this site. If you are looking for web hosting services, you have come to the right place. Please search my database of over 2400 hosting companies.

If you need any help, please email me at terence @ hostpulse.com . I will personally try to reply your email within a day and give you some basic guidelines, negotiate with a few hosts to offer you good pricing or answer any hosting related problems that you may have. 
Cheap Web Hosting ASP & ASP.Net Hosting

Dedicated Server

Windows Server Hosting Ecommerce Hosting PHP Hosting
Linux & Unix Hosting Cold Fusion Hosting South America
Europe Reseller Hosting Managed Hosting
Virtual Private Server Asia Pacific Search by Country

Reference and Manual


Hosting Glossary  PHP  HTML 4.01  CSS 2.0  Core Javascript 1.5  XHTML 1.0

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 implements Reflector { }
  class
ReflectionParameter implements Reflector { }
  class
ReflectionMethod extends ReflectionFunction { }
  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 18-27. Basic usage of the reflection API

<?php
  Reflection
::export(new ReflectionClass('Exception'));
?>
We will see:
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> method __construct ] {
    }

    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 ] {
    }
  }
}

ReflectionFunction

The ReflectionFunction class lets you reverse-engineer functions.

<?php
  
class ReflectionFunction implements Reflector {
      
public object __construct(string name)
      
public string __toString()
      
public static string export()
      
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 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 18-28. Using the ReflectionFunction class

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

    return
$c++;
}

// Create an instance of the Reflection_Function 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());


// 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 {
      
public object __construct(string name)
      
public string __toString()
      
public static string export()
      
public string getName()
      
public ReflectionClass getClass()
      
public bool allowsNull()
      
public bool isPassedByReference()
      
public bool isOptional()
  }
?>

Note: isOptional() was added in PHP 5.1.0.

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 18-29. 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 Reflection_Function 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.

<?php
  
class ReflectionClass implements Reflector {
      
public __construct(string name)
      
public string __toString()
      
public static string export()
      
public string getName()
      
public bool isInternal()
      
public bool isUserDefined()
      
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 bool isInstantiable()
      
public bool isInterface()
      
public bool isFinal()
      
public bool isAbstract()
      
public int getModifiers()
      
public bool isInstance(stdclass object)
      
public stdclass newInstance(mixed* args)
      
public ReflectionClass[] getInterfaces()
      
public ReflectionClass getParentClass()
      
public bool isSubclassOf(ReflectionClass class)
  }
?>

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 18-30. 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').

ReflectionMethod

The ReflectionMethod class lets you reverse-engineer class methods.

<?php
  
class ReflectionMethod extends ReflectionFunction {
      
public __construct(mixed class, string name)
      
public static string export()
      
public mixed invoke(stdclass object, mixed* args)
      
public bool isFinal()
      
public bool isAbstract()
      
public bool isPublic()
      
public bool isPrivate()
      
public bool isProtected()
      
public bool isStatic()
      
public bool isConstructor()
      
public int getModifiers()
      
public ReflectionClass getDeclaringClass()

      
/* Inherited from ReflectionFunction */
      
public string __toString()
      
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()
  }
?>

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 18-31. Using the ReflectionMethod class

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

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

  
// Create an instance of the Reflection_Method 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() ? ' private' : '',
    
$method->isProtected() ? ' protected' : '',
    
$method->isStatic() ? ' static' : '',
    
$method->getName(),
    
$method->isConstructor() ? 'the constructor' : 'a regular method',
    
$method->getFileName(),
    
$method->getStartLine(),
    
$method->getEndline(),
    
$method->getModifiers(),
    
implode(' ', Reflection::getModifierNames($method->getModifiers()))
  );

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

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

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

Note: Trying to invoke private, protected or abstract methods will result in an exception being thrown from the invoke() method.

Note: For static methods as seen above, you should pass NULL as the first argument to invoke(). For non-static methods, pass an instance of the class.

ReflectionProperty

The ReflectionProperty class lets you reverse-engineer class properties.

<?php
  
class ReflectionProperty implements Reflector {
      
public __construct(mixed class, string name)
      
public string __toString()
      
public static string export()
      
public string getName()
      
public bool isPublic()
      
public bool isPrivate()
      
public bool isProtected()
      
public bool isStatic()
      
public bool isDefault()
      
public int getModifiers()
      
public mixed getValue(stdclass object)
      
public void setValue(stdclass object, mixed value)
      
public ReflectionClass getDeclaringClass()
  }
?>

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

Example 18-32. Using the ReflectionProperty class

<?php
  
class String
  
{
      
public $length  = 5;
  }

  
// Create an instance of the ReflectionProperty class
  
$prop = new ReflectionProperty('String', 'length');

  
// Print out basic information
  
printf(
      
"===> The%s%s%s%s property '%s' (which was %s)\n".
      
"     having the modifiers %s\n",
      
$prop->isPublic() ? ' public' : '',
      
$prop->isPrivate() ? ' private' : '',
      
$prop->isProtected() ? ' protected' : '',
      
$prop->isStatic() ? ' static' : '',
      
$prop->getName(),
      
$prop->isDefault() ? 'declared at compile-time' : 'created at run-time',
      
var_export(Reflection::getModifierNames($prop->getModifiers()), 1)
  );

  
// Create an instance of String
  
$obj= new String();

  
// Get current value
  
printf("---> Value is: ");
  
var_dump($prop->getValue($obj));

  
// Change value
  
$prop->setValue($obj, 10);
  
printf("---> Setting value to 10, new value is: ");
  
var_dump($prop->getValue($obj));

  
// Dump object
  
var_dump($obj);
?>

Note: Trying to get or set private or protected class property's values will result in an exception being thrown.

ReflectionExtension

The ReflectionExtension class lets you reverse-engineer extensions. You can retrieve all loaded extensions at runtime using the get_loaded_extensions().

<?php
  
class ReflectionExtension implements Reflector {
      
public __construct(string name)
      
public string __toString()
      
public static string export()
      
public string getName()
      
public string getVersion()
      
public ReflectionFunction[] getFunctions()
      
public array getConstants()
      
public array getINIEntries()
  }
?>

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

Example 18-33. Using the ReflectionExtension class

<?php
  
// Create an instance of the ReflectionProperty class
  
$ext = new ReflectionExtension('standard');

  
// Print out basic information
  
printf(
      
"Name        : %s\n".
      
"Version     : %s\n".
      
"Functions   : [%d] %s\n".
      
"Constants   : [%d] %s\n".
      
"INI entries : [%d] %s\n",
      
$ext->getName(),
      
$ext->getVersion() ? $ext->getVersion() : 'NO_VERSION',
      
sizeof($ext->getFunctions()),
      
var_export($ext->getFunctions(), 1),
      
sizeof($ext->getConstants()),
      
var_export($ext->getConstants(), 1),
      
sizeof($ext->getINIEntries()),
      
var_export($ext->getINIEntries(), 1)
  );
?>

Extending the reflection classes

In case you want to create specialized versions of the built-in classes (say, for creating colorized HTML when being exported, having easy-access member variables instead of methods or having utility methods), you may go ahead and extend them.

Example 18-34. Extending the built-in classes

<?php
  
/**
   * My Reflection_Method class
   *
   */
  
class My_Reflection_Method extends ReflectionMethod {
    
public $visibility= '';

    
public function __construct($o, $m) {
      
parent::__construct($o, $m);
      
$this->visibility= Reflection::getModifierNames($this->getModifiers());
    }
  }

  
/**
   * Demo class #1
   *
   */
  
class T {
    
protected function x() {}
  }

  
/**
   * Demo class #2
   *
   */
  
class U extends T {
    function
x() {}
  }

  
// Print out information
  
var_dump(new My_Reflection_Method('U', 'x'));
?>

Note: Caution: If you're overwriting the constructor, remember to call the parent's constructor _before_ any code you insert. Failing to do so will result in the following: Fatal error: Internal error: Failed to retrieve the reflection object

Web Hosting Showcase
View the web hosting showcase to find more relevant web hosting choice that will guide you in selecting a good web hosting company.
 

Cheap Web Hosting ASP & ASP.Net Hosting Dedicated Servers
Windows 2000 & 2003 Server Hosting Ecommerce Hosting PHP Hosting
Linux & Unix Hosting Cold Fusion Hosting South America
Europe Reseller Hosting Managed Hosting
Virtual Private Server Asia Pacific  

Web Hosting and Development Tools

Network Tools  Download Template  Programming Manuals  Developer Tools

  

HostForWeb  HostForWeb.com
20GB Transfer, Unlimited Subdomans & E-mails, Smaller package 200MB - $9.95
ApolloHosting - Fast & Reliable Web Site Hosting  Apollo Hosting
Cnet User Recommended - Cnet Certified
HostwayVPS  Hostway Corporation
Dedicated server performance, at a fraction of normal dedicated server prices
Looking for dedicated servers in the U.K. ?  Xilo
XILO can provide dedicated servers with serveral different configurations.
SingleHop  SingleHopSingleHop
Intel Pentium D 945 with 1GB Ram, 320Gb hard disk & 2500Gb bandwidth at US$159 per month










Hosts we like
ApolloHosting
Whosbehindyourwebsite
IPowerWeb.com
WSServers
HostForWeb.com
ActiveHost
Cravis
Galaxyvisions.com
Grabweb.net
HostColor.com
Inetu.net
Lunarpages.com
Olm.net
Razorservers
Server4you.com
ServerDispatch
Shinjiru.com
Singlehop.com



Net Host Tools

Feature Host







This site provide free reviews of web hosting services from 100 selected companies. There are over 3000 over website hosting companies on the internet. Please research these domain hosting services carefully before you sign up with any. Read articles on web page hosting, web site hosting, domain names, website speed test, cheap web hosting services, PHP scripts, mysql database, asp hosting and virtual private server to gain a better knowledge on domain hosting and cheap web hosting.

 

Partners
Free Web Hosting Directory  All The Websites Promotion  Webmaster Forums  Web Hosting Services  Review Web Design Dedicated Servers Web Hosting windows reseller hosting linux , dedicated server hosting



Learn more about us
About HostPulse
Contact Us Terms of Use


©2000 - 2008 Webtrent Technology Pte Ltd
All rights reserved.

This site is hosted by ActiveHost. The company understands uptime urgency and is fanatical about hosting reliability.

A list of good and honest hosting companies.
Questions? Comments? Get started
Affordable Advertising | Host Login & Register
Submission
Submit a news | Submit a resource
Exchange links? Email Anna @ hostpulse.com
Web Hosting and Development Tools
Network Tools  Download Template  Programming Manuals   Search by Country   Links to other sites