ReflectionProperty

The ReflectionProperty class lets you reverse-engineer class properties.

<?php
  class ReflectionProperty implements Reflector {
      public __construct(mixed class, string name)
      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()
      public string toString()
  }
?>

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 14-6. 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.