What are the definition methods of PHP constants
Constant
Features: Cannot be modified, cannot Destroyed and cannot be deleted. After declaring a constant, the constant can be used anywhere on the page
Methods for declaring constants: const, define, static
Naming convention: and The variables are the same, but all capitalized
define: define is a function, which cannot be defined in an object, but can be defined and used in a class;
define('CL',10); echo CL; //判断常量是否存在 if(defined('CL')){ echo 'ture'; }else{ echo 'false'; }
static: Static constant
Static constant: It is a variable that can be accessed using constant syntax, which is::, and can be accessed without instantiation
Note: static is only initialized once and called recursively will not be repeatedly initialized
//定义静态常量 class Person{ public static $a = "呵呵"; public static function say(){ echo "我丢:".self::$a."<br>"; } } //输出静态属性 echo Person::$a."<br>"; //调用静态方法 Person::say(); //修改静态属性 Person::$a = "我靠"; echo Person::$a."<br>";
const: const is a language structure, which is faster than define when compiling. It is a global constant that can be defined in an object and used in a class. It can be understood as Class constants
class CL { //定义常量 const CLS = '常量值'; function a() { //调用常量方法 echo self::CLS; } } (new CL)->a();
Recommended tutorial: "php tutorial"
The above is the detailed content of What are the ways to define php constants?. For more information, please follow other related articles on the PHP Chinese website!