Reputation: 502
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
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
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
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