Prototypal inheritance in PHP (like in JavaScript)

时光总嘲笑我的痴心妄想 提交于 2020-01-03 08:50:13

问题


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:


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



来源:https://stackoverflow.com/questions/2192049/prototypal-inheritance-in-php-like-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!