#development #pattern #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:

1public static function getProperty($object, $property)
2{
3    $reflectedClass = new \ReflectionClass($object);
4    $reflection = $reflectedClass->getProperty($property);
5    $reflection->setAccessible(true);
6    return $reflection->getValue($object);
7}

There is however another way to do this without having to use reflection. You can achieve the same using closures (aka. arrow functions):

1public static function getProperty($object, $property)
2{
3    return (fn () => $this->{$property})->call($object);
4}

You can also use this to call private or protected methods on the object.