class Person { public $name; private $age; protected $email; public function __construct($name, $age, $email) { $this->name = $name; $this->age = $age; $this->email = $email; } } $person = new Person("John", 30, "john@example.com"); $reflection = new ReflectionObject($person); $properties = $reflection->getProperties(); foreach ($properties as $property) { echo $property->getName() . "\n"; }
class Animal { public $species; private $habitat; protected $food; public function __construct($species, $habitat, $food) { $this->species = $species; $this->habitat = $habitat; $this->food = $food; } } $animal = new Animal("lion", "savanna", "meat"); $reflection = new ReflectionObject($animal); $properties = $reflection->getProperties(ReflectionProperty::IS_PRIVATE); foreach ($properties as $property) { $property->setAccessible(true); // needed to access private properties echo $property->getName() . " = " . $property->getValue($animal) . "\n"; }This example defines an Animal class with three properties and uses ReflectionObject to obtain only the private ones. The loop then uses ReflectionProperty's setAccessible() method to access and print the private property values. The output of the loop will be: "habitat = savanna". The package library for ReflectionObject and its related classes is part of PHP's core runtime and can be found at http://php.net/manual/en/book.reflection.php.