您知道Php 7.2具有类型化属性:
class Test { }
class Test2
{
private Test $test;
public function __construct()
{
$this->test = new Test();
}
}
到目前为止还不错,但是如果我想要一个懒惰创建的对象呢?
public function createIfNotExists()
{
if ($this->test === null) // *ERROR
{
}
}
此操作失败:
初始化之前,不得访问类型化属性
但我想检查它是否已创建,而不是使用它。如何?
您可能可以进行
isset($this->test)
从PHP 7.4开始,您也可以在方法中使用Null合并赋值运算符??=
public function createIfNotExists()
{
$this->test ??= new Test();
}
它相当于
$this->test = $this->test ?? new Test();
相当于
$this->test = isset($this->test) ? $this->test : new Test();