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
我可以定义整个动物园,它非常棒,但是我无法在 zoo 中找到我的动物,因为我能找到它单一的动物。这在现实世界中是合理的,但如果我没有错过任何东西,这就是补充问题。
是故意定义的();不接受数组?如果我定义我的动物园...
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
当狗确实不存在时显示通知+警告
/** 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。无论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";
答案 0 :(得分:9)
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";