php – 与其他特征方法的冲突
如何用同名方法处理特征?
trait FooTrait { public function fooMethod() { return 'foo method'; } public function getRow() { return 'foo row'; } } trait TooTrait { public function tooMethod() { return 'too method'; } public function getRow() { return 'too row'; } } class Boo { use FooTrait; use TooTrait; public function booMethod() { return $this->fooMethod(); } } 错误,
我该怎么办? 而且,使用两个相同的方法名称,如何从trait FooTrait获取该方法? $a = new Boo; var_dump($a->getRow()); // Fatal error: Call to undefined method Boo::getRow() in... 编辑: class Boo { use FooTrait,TooTrait { FooTrait::getRow insteadof TooTrait; } public function booMethod() { return $this->fooMethod(); } } 如果我想通过Boo从TooTrait获取getRow的方法呢?可能吗?
PHP关于冲突的文档:
<?php trait A { public function smallTalk() { echo 'a'; } public function bigTalk() { echo 'A'; } } trait B { public function smallTalk() { echo 'b'; } public function bigTalk() { echo 'B'; } } class Talker { use A,B { B::smallTalk insteadof A; A::bigTalk insteadof B; } } class Aliased_Talker { use A,B { B::smallTalk insteadof A; A::bigTalk insteadof B; B::bigTalk as talk; } } 所以在你的情况下可能是 class Boo { use FooTrait,TooTrait { FooTrait::getRow insteadof TooTrait; } public function booMethod() { return $this->fooMethod(); } } (即使你单独使用也可以工作,但我认为更清楚) 或者使用as来声明一个别名. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |