Home >Backend Development >PHP Tutorial >Detailed explanation of the difference between define() and const in php_PHP tutorial
In PHP, both define() and const() can define constants. So what is the difference between define() and const? Many programmers don’t understand this. Let me introduce to you some usage comparisons of this function. Right.
The difference between define() and const:
define() defines constants at execution time, while const defines constants at compile time. There is a slight speed advantage to const (i.e. slightly better performance), but it's not worth considering unless you're building a heavily concurrent system.
define() puts the constant into the global scope. Even if the constant is defined using the define method in the namespace, it still belongs to the global scope. You cannot use define() to define class constants (class constants are defined using const), and constants within the namespace scope are defined using const, such as: namespace const ABC=’100′;.
define() allows you to use expressions in constant names and constant values, while const does not allow either. This makes define() more flexible.
define() can be called within an if() block, but const cannot.
In the same scope, the define() constant name and the constant name defined by const cannot be the same.
const can define class constants and namespace constants. Such as
namespace abc; const ABC = ‘a’; class hello { const C_NUM = 8; }
The code is as follows
|
Copy code
|
||||||||||||
Const FOO = 'BAR'; // invalid }
but
Define('FOO', 'BAR'); // valid |
The code is as follows |