In PHP, a constant is an immutable value that cannot be reassigned or deleted once defined. Defining constants ensures code reusability and readability, while also improving code performance. This article will introduce how to define constants in PHP.
The syntax for defining constants in PHP is as follows:
define(name, value, case_insensitive);
This syntax has three parameters:
Here is an example:
define("GREETING", "Hello World!"); echo GREETING;
This code will output "Hello World!" because GREETING has been defined as a constant. Note that constant names are usually expressed in uppercase letters as a matter of convention.
In PHP, the scope of constants is different from that of variables. Constants can be defined and accessed anywhere, including within functions, classes, and the global scope. Constant names are not scoped and therefore can be accessed anywhere.
Here is an example:
// 在全局作用域内定义常量 define("GREETING", "Hello World!"); function sayHello() { // 在函数内访问常量 echo GREETING; } class MyClass { // 在类内定义常量 const PI = 3.14; public function getPi() { // 在类中访问常量 return self::PI; } } // 在脚本的任何地方都可以访问常量 echo GREETING; echo MyClass::PI;
PHP also has some predefined constants, which are usually used to store things like server paths. , current script name and other common information. The following are some commonly used predefined constants:
The following is an example, using predefined constants to output the path of the current file, the line number of the current code line and the current PHP version number:
echo __FILE__ . "<br>"; echo "The line number is " . __LINE__ . "<br>"; echo "PHP version is " . PHP_VERSION . "<br>";
The output results are as follows:
/Users/me/example.php The line number is 8 PHP version is 7.4.12
Defining constants in PHP is very simple, just use the define() function. Constants have a different scope than variables and can be defined and accessed anywhere. In addition, PHP also provides some predefined constants for storing commonly used information. Being proficient in the use of constants will help you write high-quality, reusable PHP code.
The above is the detailed content of How to define constants in PHP. For more information, please follow other related articles on the PHP Chinese website!