HAYCORN — 6 July 2011

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 pro­tected prop­er­ties and methods of Base even in the case where an in­stance of Base is merely the ar­gu­ment to some method. (I ex­pected 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 func­tions are static, leading to a generic way to modify pro­tected properties:

class Foo {

 pro­tected $message = "jjj";

}

class Foo_Wrap­per extends Foo {

 // Allows you to set both public and pro­tected (!) prop­er­ties

 static func­tion set($obj, $property, $value) {
 $obj->{$property} = $value;
 }

 // Allows you to get both public and pro­tected (!) prop­er­ties

 static func­tion get($obj, $property) {
 return $obj->{$property};
 }

}

$obj = new Foo();

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

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