Php 简明教程

PHP - Constant Arrays

在 PHP 5.6 版本之前,无法声明常量数组。从 PHP 5.6 开始,可以使用“const”关键字声明常量数组。从 PHP 7 开始,常量数组也可以通过 define() 函数来形成。

常量数组是形成后无法修改的数组。与普通数组不同,它的标识符不以“$”符号开头。

声明常量数组的较旧语法为:

const ARR = array(val1, val2, val3);

Example

<?php
   const FRUITS = array(
      "Watermelon",
      "Strawberries",
      "Pomegranate",
      "Blackberry",
   );
   var_dump(FRUITS);
?>

它将生成以下 output

array(4) {
   [0]=>
   string(10) "Watermelon"
   [1]=>
   string(12) "Strawberries"
   [2]=>
   string(11) "Pomegranate"
   [3]=>
   string(10) "Blackberry"
}

您还可以在 PHP 中使用传统的方括号语法来声明常量数组:

const FRUITS = [
   "Watermelon",
   "Strawberries",
   "Pomegranate",
   "Blackberry",
];

Example

无法修改常量数组中的任何元素。因此,以下代码会引发致命错误:

<?php
   const FRUITS = [
      "Watermelon",
      "Strawberries",
      "Pomegranate",
      "Blackberry",
   ];
   FRUITS[1] = "Mango";
?>

它将生成以下 output

PHP Fatal error:  Cannot use temporary expression in write context

Constant Arrays PHP 7 Onwards

较新版本的 PHP 允许您通过 define() 函数来声明常量数组。

<?php
   define ('FRUITS',  [
      "Watermelon",
      "Strawberries",
      "Pomegranate",
      "Blackberry",
   ]);
   print_r(FRUITS);
?>

它将生成以下 output

Array
(
   [0] => Watermelon
   [1] => Strawberries
   [2] => Pomegranate
   [3] => Blackberry
)

您还可以使用 array() 函数在此声明常量数组。

define ('FRUITS',  array(
   "Watermelon",
   "Strawberries",
   "Pomegranate",
   "Blackberry",
));

Example

也可以声明一个 associative constant array 。以下是一个示例:

<?php
   define ('CAPITALS',  array(
      "Maharashtra" => "Mumbai",
      "Telangana" => "Hyderabad",
      "Gujarat" => "Gandhinagar",
      "Bihar" => "Patna"
   ));
   print_r(CAPITALS);
?>

它将生成以下 output

Array
(
   [Maharashtra] => Mumbai
   [Telangana] => Hyderabad
   [Gujarat] => Gandhinagar
   [Bihar] => Patna
)