如何检查定义的常量数组中是否存在数组键 [PHP 7 define()]

How to check does array key exist in defined constant array [PHP 7 define()]

PHP7 带来了使用 define() 定义数组常量的可能性。在 PHP 5.6 中,它们只能用 const.

定义

所以我可以使用 define( string $name , mixed $value )) to set array of constants, but it seems that it forgot to bring also upgrade of defined ( mixed $name ),因为它仍然只接受 string 值,还是我遗漏了什么?

PHP v: < 7 我必须分别定义每个动物 define('ANIMAL_DOG', 'black');define('ANIMAL_CAT', 'white'); 等,或者序列化我的 zoo.

PHP v: >= 7 我可以定义整个 zoo 这太棒了,但是我在 zoo[=63= 中找不到我的动物] 因为我可以简单地找到单个动物。这在现实世界中是合理的,但如果我没有错过任何东西,这里是补充问题。

是故意定义的();不接受数组?如果我定义我的动物园...

define('ANIMALS', array(
    'dog' => 'black',
    'cat' => 'white',
    'bird' => 'brown'
));

...为什么我找不到我的狗 defined('ANIMALS' => 'dog');

1. 始终打印:The dog was not found

print (defined('ANIMALS[dog]')) ? "1. Go for a walk with the dog\n" : "1. The dog was not found\n";

2. 总是打印:The dog was not found 当狗真的不存在时显示 Notice + Warning

/** if ANIMALS is not defined
  * Notice:  Use of undefined constant ANIMALS - assumed ANIMALS...
  * Warning:  Illegal string offset 'dog'
  * if ANIMALS['dog'] is defined we do not get no warings notices
  * but we still receive The dog was not found */
print (defined(ANIMALS['dog'])) ? "2. Go for a walk with the dog\n" : "2. The dog was not found\n";

3. 无论是否定义了 ANIMALSANIMALS['dog'],我都会收到警告:

/* Warning:  defined() expects parameter 1 to be string, array given...*/  
print defined(array('ANIMALS' => 'dog')) ? "3. Go for a walk with the dog\n" : "3. The dog was not found\n";

4. 如果未定义 ANIMALS['dog'] 我会收到通知

/* Notice: Use of undefined constant ANIMALS - assumed 'ANIMALS' */
print (isset(ANIMALS['dog'])) ? "4. Go for a walk with the dog\n" : "4. The dog was not found\n";

5.那我说的只有一个选项对吗?

print (defined('ANIMALS') && isset(ANIMALS['dog'])) ? "Go for a walk with the dog\n" : "The dog was not found\n";

PHP 7 允许您 define 常量数组,但在这种情况下被定义为常量的是 数组本身 ,而不是它的各个元素。在其他方面,常量函数作为一个典型的数组,因此您需要使用常规方法来测试其中是否存在特定键。

试试这个:

define('ANIMALS', array(
    'dog'  => 'black',
    'cat'  => 'white',
    'bird' => 'brown'
));

print (defined('ANIMALS') && array_key_exists('dog', ANIMALS)) ?
    "Go for a walk with the dog\n" : "The dog was not found\n";