PHP constantsLOGIN

PHP constants

Constantcan be understood as: a permanent value

After a constant value is defined, it cannot be changed anywhere else in the script


#PHP Constants

A constant is an identifier (name) of a single value. This value cannot be changed in script.

Valid constant names start with a character or an underscore (there is no $ sign in front of the constant name).

Constant names can be lowercase, but usually uppercase

Note: Unlike variables, constants are automatically global throughout the entire script.


#Set PHP constants
To set a constant, use the define() function - it uses three parameters:

1. The first parameter defines the name of the constant

2. The second parameter defines The value of the constant

3. The optional third parameter specifies whether the constant name is case-sensitive. The default is false.

Example

The following example creates a case-sensitive constant whose value For "Welcome to PHP.cn!":

<?php
 define("GREETING", "Welcome to PHP.cn!");
 echo GREETING;
 ?>

You can change the constant name of echo above to lowercase and try to see what will be output


##ExampleThe following example creates a size-insensitive constant with the value "Welcome to PHP.cn!":

<?php
 define("GREETING", "Welcome to PHP.cn!",true);
 echo greeting;
 ?>


Constants are global

After a constant is defined, it defaults to a global variable and can be used in the entire running script. Use anywhere.

Example

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

<?php
 header("Content-type:text/html;charset=utf-8");
 define("GREETING", "欢迎访问 php.cn");
 
 function myTest() {
     echo GREETING;
 }
 
 myTest();    // 输出 "欢迎访问 php.cn"
 ?>

In addition, the system also prepares some built-in constants for us. These constants are specified. Let’s get familiar with a few first, and there are more system constants that can be slowly added and learned after getting started.

##Constant name Description LINEThe current line FILEThe path of the current file on the server FUNCTIOINCurrent function name CLASSCurrent class name


## METHODCurrent member method name PHP_OSThe operating system that PHP runs on PHP_VERSIONCurrent PHP version TRAITTrait Name, added in php5.4## DIR
The directory where the file is located



NAMESPACE
The name of the current namespace (case sensitive)


Next Section

<?php header("Content-type:text/html;charset=utf-8"); define("GREETING", "欢迎访问 php.cn"); function myTest() { echo GREETING; } myTest(); // 输出 "欢迎访问 php.cn" ?>
submitReset Code
ChapterCourseware