PHP 5.4:为什么类可以用不同的签名覆盖特征方法? [英] PHP 5.4: why can classes override trait methods with a different signature?

查看:90
本文介绍了PHP 5.4:为什么类可以用不同的签名覆盖特征方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在当前的PHP 5.4实现中是否有任何理由可以解释这种行为:

I'm wondering if there is any good reason why this behaviour is possible in the current PHP 5.4 implementation:

trait T {
    public function test(PDO $pdo) {}
}

class C {
    use T;
    public function test(DOMDocument $dom) {}
}

我以为一个类使用特征的事实,保证这个类有一个特定的接口可用。但是在这里,如果我们无意中为了其他目的而无意中覆盖了特征方法,我们甚至没有像经典继承那样收到严格标准通知。

I thought that the fact that a class uses a trait, guaranteed that this class had a specific interface available. But here, if we inadvertently override the trait method for another purpose, we don't even receive a Strict Standards notice, as with classic inheritance.

这是否特别允许目的?为什么?

Is this specifically allowed on purpose? What for?

推荐答案

记录此行为。来自php.net( http://php.net/manual/en/language。 oop5.traits.php ):

This behavior is documented. From php.net (http://php.net/manual/en/language.oop5.traits.php):


基类的继承成员被插入的成员
覆盖特质。优先顺序是来自
当前类的成员覆盖Trait方法,这些方法返回覆盖
继承的方法。

An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in return override inherited methods.

没有理由在这里发出通知。

No reason for notices here.

编辑:

我拿了一个看一些更严肃的文献来阐明这个话题:)。看起来这种行为是特质定义的一部分。他们是以这种方式工作的。这来自研究特征:可组合行为单位(欧洲面向对象程序设计会议论文集):

I took a look on some more serious literature to shed some light on this topic :) . Looks like that such behavior is a part of traits' definition. They are ment to work this way. This is from research "Traits: Composable Units of Behavior"(Proceedings of the European Conference on Object-Oriented Programming):


另一个属性特质组成是组合顺序是
无关紧要,因此冲突特征方法必须明确
消除歧义(参见第3.5节)。在
类中定义的方法和由合并特征定义的方法之间的冲突使用
解决以下两个优先规则。

Another property of trait composition is that the composition order is irrelevant, and hence conflicting trait methods must be explicitly disambiguated (cf. section 3.5). Conflicts between methods defined in classes and methods defined by incorporated traits are resolved using the following two precedence rules.

- 类方法优先于特征方法。

– Class methods take precedence over trait methods.

- 特征方法优先于超类方法。这来自fl atte用属性,该属性表明特征方法的行为就好像它们是在类本身中定义的那样。

– Trait methods take precedence over superclass methods. This follows from the flattening property, which states that trait methods behave as if they were defined in the class itself.

你可以阅读更多这里: http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf

You can read more here: http://scg.unibe.ch/archive/papers/Scha03aTraits.pdf

这篇关于PHP 5.4:为什么类可以用不同的签名覆盖特征方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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