This article mainly introduces the difference between define and const in PHP, has a certain reference value, now share to everyone, the need for friends can refer to
We often define non-constant values as constants, which are usually represented in all capitals, with no dollar sign ahead, so what is the difference between define and const?
A constant is a simple identifier. This value cannot be changed during script execution (in addition to the so-called magic constants, they are not constants). Constants are case sensitive by default. Usually, constant identifiers are always uppercase.
You can use the Define () function to define constants. After php5.3.0, you can use the Const keyword to define constants outside the class definition, PHP7 can define array constants, and the previous version of the Const keyword can only be used in class. Once a constant is defined, it can no longer be changed or undefined.
<?php//The following code can work correctly after PHP 5.3.0 const USERNAME = ' Botong pass '; Echo USERNAME. PHP_EOL;ECHO constant ("USERNAME"); const Zhouusername = ' Zhou Botong nine yin Canon ';d efine (' myusername ', ' Zhou Botong nine Yin Canon 2 '); echo "<pre>" ;p Rint_r (Get_defined_constants ());? >
Constants and variables have the following differences:
1, const is a language structure, and define is a function that can be specified by the third argument for case sensitivity. True to indicate case insensitive, default to False
2. Const is easy to read and compiles much faster than define.
3, the const can be used in the class, for the class member constant definition, after definition cannot be modified; Define cannot be used in a class, can be used for global variables
<?phpclass myclass{ Const USER = ' Botong pass '; function Showconstant () { echo self::user. Php_eol; echo constant (' USER ');//Note: Warning:constant (): couldn ' t find constant USER }} $class = new MyClass (); $class-& Gt;showconstant ();
4, const is defined at compile time, so must be at the top of the scope, not in the function, loop and if conditions, and define is a function, that is, can call the function of the place can be used
<?php$x = true;if ($x ==1) { //const FOO = ' BAR '; Invalid invalid}if ($x ==1) { define (' FOO ', ' BAR ');//Valid valid echo FOO;}
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!