开发者

Prototypal inheritance in PHP (like in JavaScript)

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 wi开发者_StackOverflow中文版th 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();


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜