views:

89

answers:

1

Is it possible to employ some kind of prototypal inheritance in PHP like it is implemented in JavaScript?

This question came to my mind just out of curiosity, not that I have to implement such thing and go against classical inheritance. It just feels like a interesting area to explore.

Are there prebuild functions to combine classical inheritance model in PHP with some sort of Prototypal inheritance with a combination of anonymous functions?

Let's say I have a simple class for UserModel

class UserModel implements PrototypalInheritance
{
    // setters, getters, logic..
    static public function Prototype () {}
}

$user = new UserModel();

UserModel::prototype()->getNameSlug = function () {
    return slugify($this->getUserName());
}

echo $user->getNameSlug();
+1  A: 

You can use the Prototype Creational Pattern to achieve something somewhat similar to this, but real prototypical inheritance like found in JavaScript is not possible afaik.

If you are looking to have something like mixins/traits, you could use Decorators.

There is an RFC about whether to have traits in PHP6 though.

What you could do, is have Prototype pattern that tracks the lifecycle of it's cloned objects through an SplObjectStorage. Whenever the prototype is changed, the Builder would walk through the map and adjust the instances accordingly. Monkey patching would have to be done through runkit though. Doesn't sound too feasible imho :)

Gordon
Thanks for excellent sources. Traits in PHP6 look interesting, hovewer nowadays it's hard to find webhosting even with `PHP 5.3.0` (required for anonymous magic :-D)..The Prototype patterns looks promising. Decorators look like they would break up the simplicity of Proto, as they require some sort of Dependency Injection
Juraj Blahunka