In php, both define () and const () can define constants. So what is the difference between define () and const? many programmers do not understand this, I will introduce you
In php, both define () and const () can define constants. So what is the difference between define () and const? many programmers do not understand this, next I will introduce you to the usage comparison of this function.
Difference between define () and const:
Define () defines constants during execution, while const defines constants during compilation. In this way, const has a slight speed advantage (better performance), but it is not worth considering unless you are building a large high concurrency system.
Define () puts constants in the global scope, even if the define method is used to define constants in the namespace, it also belongs to the global scope. You cannot use define () to define class constants (class constants are defined using const). constants in the namespace scope use const to define such as namespace const ABC = '000000 ′;.
Define () allows you to use expressions in constant names and constant values, while const does not. This makes define () more flexible.
Define () can be called in the if () code block, but const cannot. in the same scope, the constant names of define () and const cannot be the same, const can define class constants and namespace constants. for example
Namespace abc; const ABC = 'a'; class hello {const C_NUM = 8 ;}
The code is as follows:
- If (...){
- Const FOO = 'bar'; // invalid
- }
-
- But
-
- If (...){
- Define ('foo', 'bar'); // valid
- }
Const uses a normal constant name, and define can use an expression as the name. The code is as follows:
- Const FOO = 'bar ';
- For ($ I = 0; $ I <32; ++ $ I ){
- Define ('bit _ '. $ I, 1 <$ I );
- }
Const can only accept static scalar, while define can use any expression. the code is as follows:
- Const BIT_5 = 1 <5; // invalid
- But
- Define ('bit _ 5', 1 <5); // valid
Const is always case sensitive. however, define () can use the third parameter to define a case-insensitive constant. the code is as follows:
- Define ('foo', 'bar', true );
- Echo FOO; // BAR
- Echo foo; // BAR
Summary:Const is easy to read. it is a language structure, and define is a method. it is much faster to define const in compilation than define.