Search code examples
phpstaticphp-5.6notice

Late static binding & isset in PHP prior 7.0


The following code works as expected on PHP 7.0 and newer:

class foo {
    const BLAH = [];

    public function bar() {
        return isset(static::BLAH['baz']);
    }
}

var_dump((new foo)->bar());

While PHP 5.6 just gives:

Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead)

Changing the code as suggested leads to a notice (which is expected):

Notice: Undefined index: baz

This would work:

class foo {
    const BLAH = [];

    public function bar() {
        return null !== static::BLAH['baz'];
    }
}

var_dump(@(new foo)->bar());

Is there an alternative that doesn't end in a notice, without prefixing the call with an @?


Solution

  • You can make use of array_key_exists instead, which should work without any issue with PHP5.

    return array_key_exists('baz', static::BLAH);
    

    Note that a minor difference with isset is that array_key_exists will always return true if static::BLAH['baz'] is defined, whereas isset will return false if it's defined but its value is null.