Check for elements in class array constants in PHP 5.6

How to check if a constant element such as 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

+7
php constants
source share
3 answers

isset only works with variables. You can use the following code to check if 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']) ); 
+9
source share

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

 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'])); 
+5
source share

You can also just use:

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

The only caveat is that you cannot use it if your const can be defined as NULL.
In that case, you would probably prefer the value const a '' (empty string), which is pretty similar to PHP.

0
source share

All Articles