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



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'
));

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

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

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

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 dogn" : "2. The dog was not foundn";

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 dogn" : "3. The dog was not foundn";

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

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

5.那么我说的只有一种选择是正确的吗?

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

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 dogn" : "The dog was not foundn";

最新更新