PHP

php self能否在trait中使用

小樊
83
2024-07-13 02:01:22
栏目: 编程语言

在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 方法。

0
看了该问题的人还看了