We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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:
<?php
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):
<?php
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.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.