user5483434
user5483434

Reputation: 502

Check existence of elements in a class's array constants in PHP 5.6

How can I check that a constant element like A\B::X['Y']['Z'] is set?

<?php

namespace A;

class B
{
    const X = [
        'Y' => [
            'Z' => 'value'
        ]
    ];
}

var_dump(defined('\A\B::X') && isset(\A\B::X['Y']['Z']));

Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead) in [...] on line 13

Upvotes: 10

Views: 2395

Answers (3)

cFreed
cFreed

Reputation: 4474

You also can simply use:

var_dump(@\A\B::X['Y']['Z'] !== NULL);

The only caveat is you can't use it if your const may be defined to NULL.
In such a case, you could choose to rather give the const a ''(empty string) value, which is pretty equivalent in PHP.

Upvotes: 0

Ihor Burlachenko
Ihor Burlachenko

Reputation: 4905

isset works only with variables. You can use the following code to check that A\B::X['Y']['Z'] exists:

var_dump(
    defined('\A\B::X') &&
    array_key_exists('Y', \A\B::X) &&
    array_key_exists('Z', \A\B::X['Y'])
);

Upvotes: 14

Federkun
Federkun

Reputation: 36924

Since isset works on variables (my bad) and not on arbitrary expression, you can use array_key_exists instead.

namespace A;

class B
{
    const X = [
        'Y' => [
            'Z' => 'value'
        ]
    ];
}

var_dump(array_key_exists('Y', \A\B::X) && array_key_exists('Z', \A\B::X['Y']));

Upvotes: 5

Related Questions