you know Php 7.2 has typed properties:
class Test { }
class Test2
{
private Test $test;
public function __construct()
{
$this->test = new Test();
}
}
so far so good, but what if I want to have a lazy created object?
public function createIfNotExists()
{
if ($this->test === null) // *ERROR
{
}
}
this fails:
Typed property must not be accessed before initialization
but I want to check either it's been created, not using it. How to?
isset($this->test)work?isset()or!empty()? & Use the null operator on your property:private ?Test $test = null;if (property_exists($this, "test"))is more appropriate, but Barmar is correct that you should just set it in the constructor.