php self能否在trait中使用

PHP
1337
2024/6/23 2:01:22
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: php set集合如何添加元素