在PHP中,self 关键字指的是当前类,而不是当前 trait。因此,在 trait 中使用 self 并不会指向 trait 自身。如果想要在 trait 中引用 trait 自身,可以使用 static 关键字。
例如:
trait MyTrait {
public static function myMethod() {
echo "This is a method in MyTrait";
}
public function callMyMethod() {
static::myMethod();
}
}
class MyClass {
use MyTrait;
}
$obj = new MyClass();
$obj->callMyMethod(); // This is a method in MyTrait
在上面的例子中,static::myMethod() 会调用 trait 中的 myMethod 方法。