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
A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name).
No, you can't. But you could declare it as a static property. Array const is available from PHP 5.6. @Martin Yep, that's true, but you can not declare a constant with an array.
The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.
Summary: in this tutorial, you will learn how to use the PHP in_array () function to check if a value exists in an array. The in_array () function returns true if a value exists in an array. Here’s the syntax of the in_array () function:
PHP 7 - Constant Arrays. Array constants can now be defined using the define() function. In PHP 5.6, they could only be defined using const keyword.
As of PHP 8.1.0, class constants cannot be redefined by a child class if it is defined as final . It's also possible for interfaces to have constants. Look at the interface documentation for examples. It's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self , parent and static ).
Approach 1 (Using in_array () method): The array () method can be used to declare an array. The in_array () method in PHP is used to check the presence of an element in the array. The method returns true or false depending on whether the element exists in the array or not.
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'])
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With