PHP complete se...login
PHP complete self-study manual
author:php.cn  update time:2022-04-15 13:53:54

PHP constants



#What are constants in PHP?

A constant is an identifier (name) of a simple value. Once a constant value is defined, it cannot be changed anywhere else in the script.


PHP Constants

A constant is an identifier of a simple value. This value cannot be changed in the script.

A constant consists of English letters, underscores, and numbers, but numbers cannot appear as the first letter. (The $ modifier is not required on the constant name).

Note: Constants can be used throughout the script.


Set PHP constants

To set constants, use the define() function. The function syntax is as follows:

bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )
该函数有三个参数:
  • name:Required parameter, constant name, i.e. identifier.

  • value: Required parameter, the value of the constant.

  • case_insensitive : Optional parameter, if set to TRUE, this constant is case insensitive. The default is case-sensitive.

In the following example we create a case-sensitive constant, the constant value is "Welcome to php.cn":

<?php
// 区分大小写的常量名
define("GREETING", "欢迎访问 php.cn");
echo GREETING; // 输出 "欢迎访问 php.cn"
echo '<br>';
echo greeting; // 输出 "greeting"
?>

In the following example we create a case-insensitive constant, the constant value is "Welcome to php.cn":

<?php
// 不区分大小写的常量名
define("GREETING", "欢迎访问 php.cn", true);
echo greeting;  // 输出 "欢迎访问 php.cn"
?>

Constants are global

After a constant is defined, it defaults to a global variable. Can be used anywhere throughout the running script.

The following example demonstrates the use of constants within a function. Even if the constant is defined outside the function, the constant can be used normally.

<?php
define("GREETING", "欢迎访问 php.cn");
function myTest() {
    echo GREETING;
}
 
myTest();    // 输出 "欢迎访问 php.cn"
?>

php.cn