class Foo{ private $bar; } $reflectionClass = new ReflectionClass('Foo'); $property = $reflectionClass->getProperty('bar'); if($property->isPrivate() == true){ $property->setAccessible(true); } $fooInstance = new Foo(); $property->setValue($fooInstance, 'baz'); echo $property->getValue($fooInstance); // baz
class Foo{ public $bar = 'Hello'; protected $baz = 'World'; } $reflectionClass = new ReflectionClass('Foo'); $properties = $reflectionClass->getProperties(); foreach ($properties as $property) { if($property->isProtected()){ echo $property->getName(); // baz } }In this example, we create a class `Foo` containing two properties, `bar` and `baz`. We then use reflection to get all the properties of the `Foo` class. We then loop through each property, and if the property is protected, we print out its name which is `baz`. Package Library: PHP Standard Library (Reflection API)