
Another way of accessing private and protected properties in PHP
12 Aug 2022 #pattern #development #php
In a previous article, I demonstrated how you can get a private or protected property from an object using PHP.
It used reflection to do it's thing:
public static function getProperty($object, $property){ $reflectedClass = new \ReflectionClass($object); $reflection = $reflectedClass->getProperty($property); $reflection->setAccessible(true); return $reflection->getValue($object);}
There is however another way to do this without having to use reflection. You can achieve the same using closures (aka. arrow functions):
public static function getProperty($object, $property){ return (fn () => $this->{$property})->call($object);}
You can also use this to call private or protected methods on the object.