Return "self" 用于 PHP 特征内的 return 类型的函数
Return "self" for the return type of a function inside a PHP trait
在 PHP 特征中,我可以使用 self
作为方法的 return 类型吗?它会引用导入特征的 class 吗?
<?php
declare(strict_types=1);
trait MyTrait
{
public function setSomething(array $data): self
// ^ is this ok?
{
$this->update($data);
return $this;
}
}
实际上这是您唯一可以做的事情(参考实例或class)。
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
作为方法的 return 类型吗?它会引用导入特征的 class 吗?
<?php
declare(strict_types=1);
trait MyTrait
{
public function setSomething(array $data): self
// ^ is this ok?
{
$this->update($data);
return $this;
}
}
实际上这是您唯一可以做的事情(参考实例或class)。
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。