我有以下代码作为示例。
trait sampletrait{
function hello(){
echo "hello from trait";
}
}
class client{
use sampletrait;
function hello(){
echo "hello from class";
//From within here, how do I call traits hello() function also?
}
}
我可以详细说明为什么这是必要的,但我想让这个问题保持简单。由于我的特殊情况,从类客户端扩展并不是这里的答案。
是否可以让一个特征与使用它的类具有相同的函数名称,但除了类函数之外还调用特征函数?
目前它只会使用类函数(因为它似乎覆盖了特征)
你可以这样做:
class client{
use sampletrait {
hello as protected sampletrait_hello;
}
function hello(){
$this->sampletrait_hello();
echo "hello from class";
}
}
编辑 :
哎呀,忘了 $this-> (感谢 JasonBoss)
编辑2:
刚刚对“重命名”特征函数做了一些研究。
如果您重命名一个函数但不覆盖另一个函数(请参阅示例),则这两个函数都将存在(php 7.1.4):
trait T{
public function f(){
echo "T";
}
}
class C{
use T {
f as public f2;
}
}
$c = new C();
$c->f();
$c->f2();
您只能更改可见性:
trait T{
public function f(){
echo "T";
}
}
class C{
use T {
f as protected;
}
}
$c->f();// Won't work
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)