In PHP, the define function is mainly used to define constants. In PHP 5.6 and previous versions, define can only define constants of scalar type, such as strings, integers, and boolean values. After PHP 7, the define function supports directly defining array constants, which allows us to more conveniently use arrays as unchangeable configurations or data.
Array constants refer to arrays defined in constants and cannot be modified after definition. This means that the array constants you define remain unchanged when the code is running, which is very suitable for storing configuration information, fixed parameters, etc.
PHP 7+ version supports directly defining array constants with define . The specific syntax is as follows:
define('Constant name', Array);
To give a simple example:
define('FRUITS', ['apple', 'banana', 'orange']);
After definition, you can access the array directly through the constant name:
echo FRUITS[1]; // Output banana
Here are the detailed steps to define array constants using define :
Because only PHP 7 and above supports array constants, run the following code to view the version:
echo phpversion();
If the version is lower than 7, it is recommended to upgrade the PHP version.
define('SETTINGS', [
'host' => 'gitbox.net',
'port' => 3306,
'username' => 'root',
'password' => '123456'
]);
You can access this:
echo SETTINGS['host']; // Output gitbox.net
The constant definition cannot be modified, and the following code will cause an error:
SETTINGS['host'] = 'example.com'; // Report an error:Cannot modify constant array
Complete sample code:
<?php
// 定义Array常量
define('API_ENDPOINTS', [
'login' => 'https://gitbox.net/api/login',
'logout' => 'https://gitbox.net/api/logout',
'getUser' => 'https://gitbox.net/api/user',
]);
// 访问Array常量
echo API_ENDPOINTS['login']; // Output https://gitbox.net/api/login
PHP 7 and above can directly define array constants with define .
Array constants cannot be changed after being defined, and are suitable for storing configuration information.
When accessing, you can directly pass the constant name and key.
If you are using PHP 5.x version and array constants are not supported, it is recommended to upgrade.