在 PHP trait 中,我可以使用 self
作为方法的返回类型吗?它会引用导入特征的类吗?
<?php
declare(strict_types=1);
trait MyTrait
{
public function setSomething(array $data): self
// ^ is this ok?
{
$this->update($data);
return $this;
}
}
最佳答案
事实上,这是您唯一可以做的事情(指的是实例或类)。
class TestClass {
use TestTrait;
}
trait TestTrait {
public function getSelf(): self {
echo __CLASS__ . PHP_EOL;
echo static::class . PHP_EOL;
echo self::class . PHP_EOL;
return $this;
}
}
$test = new TestClass;
var_dump($test->getSelf());
输出
TestClass
TestClass
TestClass
object(TestClass)#1 (0) {
}
工作 example .
关于php - 返回 "self"作为 PHP trait 中函数的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63227834/