Home > Article > Backend Development > What is the difference between const and define in php?
#What is the difference between const and define in php?
1. Function define can be used in both PHP4 and PHP5, while const can only be used in PHP 5.3.0 and later versions;
2. Const defined Constants are defined at compile time, while functions define at runtime.
The difference is detailed
const is to define constants in the compilation stage, and define is to define constants in the preprocessing stage
const defines constants during the compilation phase, and they must be in the topmost scope when defining constants.
So it cannot be defined in conditional statements such as if.
define defines constants, also called macro definitions. Macros can be described as replacing certain text patterns according to a series of predefined rules.
define can exist in a branch.
Theoretically, using const will be a little faster than defining.
const only accepts scalar data, (such as integer, string, boolean and float, etc.); define can accept any expression
define('BIT_5', 1<<5); constBIT_5 = 1<<5; //5.6之后才有效 从php 5.6起,const也可以接受数组和表达式 define可以接受resource类型,const不行 const常量名只能是简单字符,define可以是任意表达式 constSTR = 'string'; $i = 1; define("STR_" . $i, STR); const大小写敏感,define可以通过第三个传参控制大小写敏感。
Recommended tutorial: "PHP》
The above is the detailed content of What is the difference between const and define in php?. For more information, please follow other related articles on the PHP Chinese website!