php - 定义数组 php 的替代方法

标签 php arrays constants global scalar

我正在寻找 define('name', array) 的替代方法,因为在 define 中使用数组会给我这个错误:

Constants may only evaluate to scalar values in ...

我提到的数组只包含字符串。

最佳答案

来自 php.net...

The value of the constant; only scalar and null values are allowed. Scalar values are integer, float, string or boolean values. It is possible to define resource constants, however it is not recommended and may cause unpredictable behavior.

但是你可以使用一些技巧:

define('names', serialize(array('John', 'James' ...)));

& 使用常量值(名称)时必须使用unserialize()。这并不是那么有用,所以只需定义多个常量即可:

define('NAME1', 'John');
define('NAME2', 'James');
..

然后像这样打印:

echo constant('NAME'.$digit);

关于php - 定义数组 php 的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19444264/

相关文章:

php - SoapClient 尝试获取架构文件时出现 401 身份验证错误

c - 函数 deque 到数组不起作用

c++ - 常量的拷贝?

c++ - 使用数组作为函数输入参数

C 程序循环数组旋转因超时而终止

MySQL常量表

c - 为什么 `const` 限定符在此初始化中被丢弃?

PHP 在列表中查找数字的最有效方法

php - 仅允许(英语和阿拉伯语)使用 UTF-8 代码

php - 加密 Ajax 数据的最佳且最安全的方法是什么?