有没有办法在PHP中定义常量数组?

trr*_*rrm 7 php

有没有办法在PHP中定义常量数组?

use*_*ess 8

define('SOMEARRAY', serialize(array(1,2,3)));

$is_in_array = in_array($x, unserialize(SOMEARRAY));
Run Code Online (Sandbox Code Playgroud)

这是最接近数组常量的.


Pek*_*ica 6

不,这是不可能的.从手册:常量语法

常量中只能包含标量数据(布尔值,整数,浮点数和字符串).可以将常量定义为资源,但应该避免,因为它可能会导致意外结果.

如果需要设置一组已定义的常量,请考虑创建一个类并使用类常量填充它.手册中略有修改的示例:

class MyClass
{
const constant1 = 'constant value';
const constant2 = 'constant value';
const constant3 = 'constant value';

  function showConstant1() {
    echo  self::constant1 . "\n";
  }
}

echo MyClass::constant3;
Run Code Online (Sandbox Code Playgroud)

另请查看GhostDog发布的链接,这是一个很好的解决方法.