PHP 5.4 : why can classes override trait methods with a different signature?

标签 php inheritance overriding traits

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

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

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

我认为类使用特征这一事实保证了该类具有可用的特定接口(interface)。但在这里,如果我们无意中出于其他目的重写了特征方法,我们甚至不会收到严格标准通知,就像经典继承一样。

这是故意允许的吗?干什么用的?

最佳答案

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

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.

此处没有通知的理由。

编辑:

我查阅了一些更严肃的文献来阐明这个主题:)。看起来这种行为是特质定义的一部分。他们被要求以这种方式工作。这是来自研究“特征:可组合的行为单元”(欧洲面向对象编程 session 记录):

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.

– 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

关于PHP 5.4 : why can classes override trait methods with a different signature?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11521403/

相关文章:

java - 需要基本的 java equals() override 帮助

php - 我做了分页,但它不能限制每页的帖子 Codeigniter

php - 导出订单详细信息 magento

多个派生类之间的 C++ 运算符重载

c# - 不能在派生类的 IEnumerable 基类上使用 LINQ 方法

java - 超子功能

php - WordPress 如何仅向订阅者授予对页面的访问权限

php - 无法创建缓存目录.. 或目录不可写。在 Laravel 中进行无缓存

C++ 用抽象类重载输入

c# - 我可以编写一个可以在继承的子项中覆盖的通用方法签名吗?