PHP 中的原型继承(如 JavaScript)
是否可以在 PHP 中使用某种原型继承,就像在 JavaScript 中实现的那样?
我出于好奇才想到这个问题,并不是说我必须实现这样的事情并违背经典继承。感觉这是一个值得探索的有趣领域。
是否有预构建函数可以将 PHP 中的经典继承模型与某种带有匿名函数组合的原型继承相结合?
假设我有一个简单的 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();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用原型创建模式来实现与此有些类似的东西,但真正的原型继承就像在JavaScript 是不可能的。
如果您正在寻找类似 mixins/traits 的东西,您可以使用 装饰器。
不过,有一个 RFC 关于 PHP6 中是否具有特征。
您可以做的是使用原型模式,通过 SplObjectStorage 跟踪其克隆对象的生命周期。每当原型发生变化时,构建器都会遍历地图并相应地调整实例。猴子修补必须通过 runkit 不过。恕我直言,听起来不太可行:)
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 :)