Reflection

The Reflection classes allow you to retrieve detailed data about classes. Although you don’t need to use them in most web applications, they’re invaluable when you’re writing a program such as a class documenter, unit tester, or debugger. These applications all require generic class-manipulation routines.

PHP 4 lets you discover information about classes using a series of functions. There’s get_class_methods( ) to get an array of class methods and get_class_vars( ) for an array of properties. These functions aren’t integrated, so you cannot find out all the information about a class at once.

The functions are also very simplistic. They don’t contain any of the new information that you can set in PHP 5. For example, there’s no way to distinguish between private, protected, and public methods and properties.

That’s where the Reflection classes come in. They help you extract from a class or method any piece of data you need.

Getting an Overview with Reflection::export

To understand how the Reflection classes work, Example 9-10 contains an example Person class that uses many of PHP 5’s OO features.

Example 9-10. Person class

class Person { public $name; protected $spouse; private $password; public function _ _construct($name) { $this->name = $name } public function getName( ) { return $name; } protected function setSpouse(Person $spouse) { if (!isset($this->spouse)) { $this->spouse = $spouse; } } private function setPassword($password) { $this->password = ...

Get Upgrading to PHP 5 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.