Last Updated: February 25, 2016
·
656
· j7mbo

Haxx your way into a class's private properties

Ever done some serious OOP using an external data source that, for some reason, provides you with data hidden away in inaccessible private / protected properties? There are a few ways to access this data, and one of them is reflection.

Let's say you have the following class:

class Kitchen
{
    protected $food = "cake";
    protected $description = "is a lie";
}

And an instance of it:

$kitchen = new Kitchen();

The following sets each member of the class to public and imports them into the current symbol table using variable variables, rather like PHP's extract():

$reflectHaxx = new ReflectionObject($kitchen);
$parsHaxx = $reflectHaxx->getProperties();

foreach ($parsHaxx as $p)
{
    // Get each property one by one...
    $property = $reflectHaxx->getProperty($p->name);
    // Set it to accessible
    $property->setAccessible('true');
    // Variable variable name and value declaration
    ${$p->name} = $property->getValue($kitchen);
}

Now, you can access $food and $description like this:

// Hint: prints "The cake is a lie!"
printf('The %s %s!', $food, $description);

Just because you can do something, however, doesn't mean you should; but if you ever find yourself in the situation where the data you're given just doesn't have the correct access modifier, give reflection a try.

This post was inspired by Ocramius's post, which shows a different method for PHP 5.4.