Home  >  Article  >  Backend Development  >  What does a php constant consist of?

What does a php constant consist of?

青灯夜游
青灯夜游Original
2019-10-11 17:15:383036browse

PHP constant is an identifier of a simple value that cannot be changed in the script; after the constant value is defined, it cannot be changed anywhere else 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).

What does a php constant consist of?

Note: Constants can be used throughout the script.

Set PHP constants

To set constants, use define() function, functionSyntax is as follows:

bool define ( string $name , mixed $value [, bool $case_insensitive = false ] )

This function has three parameters:

●name: required parameter, constant name, that is, identifier.

● Value: required parameter, the value of a 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-insensitive constant, the constant value is "Welcome to php.cn":

<?php
// 区分大小写的常量名
define("GREETING", "欢迎访问 php.cn");
echo GREETING;    // 输出 "欢迎访问 php.cn"
echo &#39;<br>&#39;;
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 and can be used throughout the Run the script anywhere it is used.

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"
?>

The above is the detailed content of What does a php constant consist of?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn