【发布时间】:2017-09-26 22:36:25
【问题描述】:
我想知道这在 PHP 中是否可行:
trait SomeTrait
{
public function someMethod() { /* ... */ }
}
class Parent
{
use SomeTrait;
}
class Child extends Parent
{
/* Do something to rename someMethod() to someOtherMethod() */
use someMethod as someOtherMethod; // Example
public function someMethod()
{
// Do something different than SomeTrait::someMethod()
}
}
在我的实际用例中,Parent 类是多个子类的父类(实际上它们都没有使用来自应用于父类的特征的someMethod()。父类类也是外部库的一部分,所以我不能直接修改源代码。
我的实际用例中的 Child 类也依赖于 Parent 类的受保护属性,因此我相当确定我需要保留继承。
这真的可能吗,还是我只需要处理它,并在有问题的 Child 类上使用不同的方法名称?
【问题讨论】:
-
你试过了吗?它应该可以正常工作,只需覆盖 trait 方法。
-
我很确定你需要在父类而不是子类中做别名。除非您只想覆盖子类中的 someMethod 实现。
-
对于Trait,手册上写得很清楚,优先顺序是当前类中的成员重写Trait方法,然后再重写继承的方法。
标签: php inheritance traits