Modifying protected properties in PHP

In a blog post, Matthew Weier O’Phinney pointed out that if class Derived extends class Base, Derived can access protected properties and methods of Base even in the case where an instance of Base is merely the argument to some method. (I expected Derived to be able to access $this->foo where $foo is protected, but I didn’t expect that Derived would be able to access $obj->foo where $obj is an argument.)

This works even if the functions are static, leading to a generic way to modify protected properties:

class Foo {

    protected $message = "jjj";

}

class Foo_Wrapper extends Foo {

    // Allows you to set both public and protected (!) properties

    static function set($obj, $property, $value) {
        $obj->{$property} = $value;
    }

    // Allows you to get both public and protected (!) properties

    static function get($obj, $property) {
        return $obj->{$property};
    }

}

$obj = new Foo();

Foo_Wrapper::set($obj, "message", "kkk");

echo Foo_Wrapper::get($obj, "message"), "\n";