Tag Archives: Reflection

Reflection

Reflection is generally defined as a program’s ability to inspect itself and modify its logic at execution time. In less technical terms, reflection is asking an object to tell you about its properties and methods, and altering those members (even private ones).

Reflection is where an object is able to introspectively examine itself to inform you of it’s methods and properties at runtime.

On the face of it this doesn’t seem like something that would be particularly useful. However, Reflection is actually a really interesting aspect of software development and it is something that you will probably touch upon often.

Following is possible using reflection

  • Analysing of nearly any aspect of classes and interfaces
  • Analysing of nearly any aspect of functions
  • Implement dynamic construction (new with variable class name)
  • useful is for debugging your code. You’ve probably used the get_class() and get_class_methods() functions when working with an ambiguously named object.
  • The ability to get the type or methods of an object when you don’t know what type of object it is, is Reflection.
  • Another common use of Reflection is for creating documentation.
  • Reflection can instantiate objects.
  • Reflection can modify static proprties of the class.
  • Reflection can get the namespace name of a class.
  • Reflection can not modify static variable in functions.

Example

<?php
 class A {
 public $one = '';
 public $two = '';
 
 public function echoOne() {
 echo $this->one."\n";
 }
 
 public function echoTwo() {
 echo $this->two."\n";
 }
 }

$a = new A();
 $reflector = new ReflectionClass('A');
 $properties = $reflector->getProperties();
 foreach($properties as $property) {
 echo "<pre>";print_r($property);
 }
?>