Jos*_*han 5 php class traits php-7 php-traits
我有以下代码作为示例.
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?
}
}
Run Code Online (Sandbox Code Playgroud)
我可以把所有细节都说明为什么这是必要的,但我想让这个问题变得简单.由于我的特殊情况,从班级客户端延伸不是答案.
是否有可能让一个特征与使用它的类具有相同的函数名称,但除了类函数之外还调用特征函数?
目前它只会使用类函数(因为它似乎覆盖了特征)
Ale*_*iet 14
你可以这样做:
class client{
use sampletrait {
hello as protected sampletrait_hello;
}
function hello(){
$this->sampletrait_hello();
echo "hello from class";
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:Whops,忘了$ 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();
Run Code Online (Sandbox Code Playgroud)
您只能更改可见性:
trait T{
public function f(){
echo "T";
}
}
class C{
use T {
f as protected;
}
}
$c->f();// Won't work
Run Code Online (Sandbox Code Playgroud)