gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:12:51 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com