0

I have class A:

class A
{
    private ?string $typed;

    public function isTypedInitialized(): bool
    {
        // ???
    }
}

How to check if $this->typed was already initialized with any value including null? isset() doesn't meet my needs, because it returns false for null.

2
  • PHP doesn't care about initialization. But why use nullable if you want it initialized to a meaningful value. What does initialization mean to you in this case? Commented Sep 13, 2021 at 18:27
  • 1
    it is for caching. If it is initialized, the data is cached and we return it from property. The data may be null as well. Commented Sep 13, 2021 at 18:40

2 Answers 2

5

I've done this check while deserialising a request to an object and checking for initialisation was a part of validation process. The solution was to use a reflection, in your example the code would be like this:

public function isTypedInitialized(): bool
{
    return (new ReflectionClass(self::class))
        ->getProperty('typed')
        ->isInitialized($this);
}

But I don't think that this checking should be the part of same class

Sign up to request clarification or add additional context in comments.

1 Comment

I'd expect something like is_initialized(), but... We have what we have.
2

If you don't want to instantiate an entire Reflection object or deal with having to use the string representation of the property (which is harder for some IDEs to understand and can be more prone to human error) you can also just rely on PHP throwing an Error if you attempt to read an uninitialized property.

public function isTypedInitialized(): bool
{
    try {
        $this->typed; // attempt to read, PHP will throw if uninitialized
        return true;
    } catch (\Error $e) {
        return false;
    }
}

If you're not yet on PHP 8.1, this is also a decent way of mimicking readonly properties:

public function setTyped(string $typed): self
{
    try {
        $this->typed; // attempt to read
    } catch (\Error $e) {
        $this->typed = $typed; // typed is uninitialized, so is ok to set
        return $this;
    }

    // if it gets here, that means PHP read the typed property without issue,
    // which means that it was already initialized.
    throw new \LogicException('property `typed` is already set');
}

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.