PHP7带来了使用define()定义数组常量的可能性。在PHP 5.6中,它们只能用const来定义。如何检查数组键是否存在于定义的常量数组中[PHP 7 define()]
所以我可以用define(string $name , mixed $value))
设置常量数组,但它似乎忘了带也沿,因为它仍然只接受string
值defined (mixed $name)
升级还是我失去了一些东西?
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');
?
版画总是: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
当狗真的不存在节目的通知+警告
/** 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";
不管是否定义了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";
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";
嘛'ANIMALS'是恒定的;而数组键“dog”只是为该常量定义的值的一部分;所以'defined()'不会在常量内检查一个值,这似乎是合乎逻辑的,只为常量本身;所以是的,逻辑上这应该是一个两步检查 –
@Mark对我来说,这似乎只是在逻辑上符合逻辑,因为PHP v <7定义应该只接受'string'; –
PHP <7将接受任何标量,而不仅仅是字符串;但检查类型和它是否被定义仍然是一个2步过程....'define('TESTMODE',true);如果(定义('TESTMODE')&& TESTMODE){ ... }' –