0

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?

4
  • 2
    Does isset($this->test) work? Commented May 4, 2021 at 21:18
  • 2
    isset() or !empty() ? & Use the null operator on your property: private ?Test $test = null; Commented May 4, 2021 at 21:18
  • 2
    If you always initialize it in the constructor, the test will never fail. Commented May 4, 2021 at 21:19
  • I think if (property_exists($this, "test")) is more appropriate, but Barmar is correct that you should just set it in the constructor. Commented May 4, 2021 at 21:30

2 Answers 2

3

you can probably do

isset($this->test)
Sign up to request clarification or add additional context in comments.

2 Comments

great, this works. I also tried to use $this->test === null, also failed.
yes because to use === you have to access the property @JohnSmith
1

As of PHP 7.4, you can use the Null Coalescing Assignment Operator ??= as well in your method

public function createIfNotExists()
{
    $this->test ??= new Test();
}

It's equivalent to

$this->test = $this->test ?? new Test();

Which is equivalent to

$this->test = isset($this->test) ? $this->test : new Test();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.