返回“self”作为 PHP 特征内函数的返回类型

Axe*_*che 4 php fluent return-type traits

在 PHP 特征中,我可以用作self方法的返回类型吗?它会引用导入该特征的类吗?

<?php

declare(strict_types=1);

trait MyTrait
{

    public function setSomething(array $data): self
                                             // ^ is this ok?
    {
        $this->update($data);
        return $this;
    }
}
Run Code Online (Sandbox Code Playgroud)

Pil*_*lan 6

事实上,这是您唯一可以做的事情(指实例或类)。

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());
Run Code Online (Sandbox Code Playgroud)

输出

TestClass
TestClass
TestClass
object(TestClass)#1 (0) {
}
Run Code Online (Sandbox Code Playgroud)

工作示例