Php 简明教程
PHP - Constant Arrays
在 PHP 5.6 版本之前,无法声明常量数组。从 PHP 5.6 开始,可以使用“const”关键字声明常量数组。从 PHP 7 开始,常量数组也可以通过 define() 函数来形成。
It was not possible to declare a constant array before PHP version 5.6. From PHP 5.6 onwards, you can use the "const" keyword to declare a constant array. From PHP 7 onwards, constant arrays can also be formed with define() function.
常量数组是形成后无法修改的数组。与普通数组不同,它的标识符不以“$”符号开头。
A constant array is an array which cannot be modified after it has been formed. Unlike a normal array, its identifier doesn’t start with the "$" sign.
声明常量数组的较旧语法为:
The older syntax for declaring constant array is −
const ARR = array(val1, val2, val3);
Example
<?php
const FRUITS = array(
"Watermelon",
"Strawberries",
"Pomegranate",
"Blackberry",
);
var_dump(FRUITS);
?>
它将生成以下 output −
It will produce the following output −
array(4) {
[0]=>
string(10) "Watermelon"
[1]=>
string(12) "Strawberries"
[2]=>
string(11) "Pomegranate"
[3]=>
string(10) "Blackberry"
}
您还可以在 PHP 中使用传统的方括号语法来声明常量数组:
You can also use the conventional square bracket syntax to declar a constant array in PHP −
const FRUITS = [
"Watermelon",
"Strawberries",
"Pomegranate",
"Blackberry",
];
Example
无法修改常量数组中的任何元素。因此,以下代码会引发致命错误:
It is not possible to modify any element in a constant array. Hence, the following code throws a fatal error −
<?php
const FRUITS = [
"Watermelon",
"Strawberries",
"Pomegranate",
"Blackberry",
];
FRUITS[1] = "Mango";
?>
它将生成以下 output −
It will produce the following output −
PHP Fatal error: Cannot use temporary expression in write context
Constant Arrays PHP 7 Onwards
较新版本的 PHP 允许您通过 define() 函数来声明常量数组。
The newer versions of PHP allow you to declare a constant array with define() function.
<?php
define ('FRUITS', [
"Watermelon",
"Strawberries",
"Pomegranate",
"Blackberry",
]);
print_r(FRUITS);
?>
它将生成以下 output −
It will produce the following output −
Array
(
[0] => Watermelon
[1] => Strawberries
[2] => Pomegranate
[3] => Blackberry
)
您还可以使用 array() 函数在此声明常量数组。
You can also use the array() function to declare the constant array here.
define ('FRUITS', array(
"Watermelon",
"Strawberries",
"Pomegranate",
"Blackberry",
));
Example
也可以声明一个 associative constant array 。以下是一个示例:
It is also possible to declare an associative constant array. Here is an example −
<?php
define ('CAPITALS', array(
"Maharashtra" => "Mumbai",
"Telangana" => "Hyderabad",
"Gujarat" => "Gandhinagar",
"Bihar" => "Patna"
));
print_r(CAPITALS);
?>
它将生成以下 output −
It will produce the following output −
Array
(
[Maharashtra] => Mumbai
[Telangana] => Hyderabad
[Gujarat] => Gandhinagar
[Bihar] => Patna
)