PHP中的原型继承(如在JavaScript中) [英] Prototypal inheritance in PHP (like in JavaScript)

查看:137
本文介绍了PHP中的原型继承(如在JavaScript中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在PHP中使用某种原型继承,就像在 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.

PHP中的将经典继承模型与某些结合使用的预构建函数原型继承与匿名函数的组合?

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

假设我有一个UserModel的简单类

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();


推荐答案

您可以使用 Prototype Creational Pattern 实现与此类似的东西,但是在JavaScript中找不到真正的原型继承。

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.

如果您希望获得类似mixins / traits的东西,可以使用装饰器

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

有一个 RFC关于是否在PHP6中具有特征

你可以做的是,有原型模式通过SplObjectStorage跟踪它的克隆对象的生命周期。每当原型发生变化时,Builder都会遍历地图并相应地调整实例。猴子补丁必须通过 runkit 尽管如此。听起来不太可行imho:)

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

这篇关于PHP中的原型继承(如在JavaScript中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆