php - 返回 "self"作为 PHP trait 中函数的返回类型

标签 php traits return-type fluent

在 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/

相关文章:

c++ - 如何在执行期间终止(或返回)具有结构类型的自动函数?

c++ - Koenig 查找的尾随返回类型和回退

php - 添加新记录时限制对数据库的访问

oop - 是否可以从特征中访问结构字段?

generics - 如何将特征绑定(bind)到非泛型类型?

c++ - 导致过载解析头痛的原因是什么?

go - 如何在函数中返回不同类型(golang)

php - 对象数组 php 的数组相交

php - 使用 NGINX 作为 apache 的反向代理时,Wordpress 永久链接返回 404

php - 包装一组 XML 节点