Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

constants

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

like image 752
user5483434 Avatar asked Jan 17 '16 21:01

user5483434


People also ask

What are PHP array constants?

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).

Can an array be a class constant?

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.

How do you check if a value exists in an associative array in PHP?

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.

How to check if a value exists in an array in PHP?

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:

How to define a constant array in PHP 7?

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.

Can a class have a constant in PHP?

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 ).

How to declare an array in PHP?

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.


1 Answers

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'])
);
like image 172
Ihor Burlachenko Avatar answered Nov 15 '22 17:11

Ihor Burlachenko