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

mku*_*gla 4 php arrays constants defined php-7

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

所以我可以define( string $name , mixed $value ))用来设置常量数组,但它似乎忘了带来升级,defined ( mixed $name )因为它仍然只接受string价值或我错过了什么?

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

PHP v: >= 7我可以定义整个动物园,这是令人敬畏的,但我在动物园找不到我的动物,因为我可以找到单一的动物.这在现实世界中是合理的,但如果我没有遗漏某些内容,这里是补充问题.

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

define('ANIMALS', array(
    'dog' => 'black',
    'cat' => 'white',
    'bird' => 'brown'
));
Run Code Online (Sandbox Code Playgroud)

......为什么我不能简单地找到我的狗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";
Run Code Online (Sandbox Code Playgroud)

2.始终打印:The dog was not found当狗真的不存在时显示通知+警告

/** 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";
Run Code Online (Sandbox Code Playgroud)

3.不管是否ANIMALS,ANIMALS['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";
Run Code Online (Sandbox Code Playgroud)

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";
Run Code Online (Sandbox Code Playgroud)

5.我也是纠正只有一个选择离开呢?

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

小智 10

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";
Run Code Online (Sandbox Code Playgroud)