The difference between define () and const in php is described in detail. 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 some differences between define () and const () in php that can define constants, many programmers do not understand this function. 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 defined by 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 } |
4. 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 ); }
|
5. 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 |
6. 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); www. bKjia. c0m 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.
Both lift () and const () can define constants. So what is the difference between define () and const? many programmers do not understand this, next I will introduce some information about this function...