PHP constantsLOGIN

PHP constants

After 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 (it is recommended to only use letters and underscores), but numbers cannot appear as the first letter. (The $ modifier is not required on the constant name).

Constant names can be lowercase, but are usually uppercase.

Constant names may not be quoted, but are usually quoted.

When calling a constant in a string, it must be outside the quotation marks.

Constants can be used throughout the script.

Set constants using the define() function. The function syntax 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, value of constant.

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

can be simply understood as:

define (constant name, constant value)

In the following example, we create a size-sensitive Write a 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 and can be used anywhere in the entire 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" 
?>

We will learn about the definition of functions later. For related information, please refer to PHP function


Next Section
<?php define('MY_NAME','PHP中文网'); echo MY_NAME; echo "<br>"; //下面是错误的调用方式 echo '我的名字是MY_NAME'; echo "<br>"; //正确的调用方式该这么写 echo '我的名字是' . MY_NAME; ?>
submitReset Code
ChapterCourseware