First, the const
PHP5.3 Previously, const can only declare variables inside a class, 5.3+ allows variables to be declared externally, but cannot be evaluated with constants!
Const one = 1; Const WORD = ' Hello World ';
PHP5.6 Start, const supports numeric expressions, including numeric, string literals, and other constants, for constant definition. And more importantly, Const begins to support defining a constant array!
Const one = 1; Const both = one * 2; Const ARR = [' A ', ' B '];
It is important to note that const does not support constant definitions of variables and methods, such as:
$path = __dir__; Const $path ; Const Ceil (7.3);
The above code will be error "Constant expression contains invalid operations".
Second, define
Before PHP5.6, the const can do, define can do! and define is supported for constants defined for variables and methods, such as:
$path = __dir__; Define $path ); Define Ceil (7.3));
But before PHP7.0, define does not support defining array constants, and if you must use them similarly, you may need to use serialize and unserialize, but it is obviously too expensive.
Define (' ARR ', [' A ', ' B ']);
The above code will be PHP7.0 before the error, 7.0+ is normal.
Iii. choice of const and define
Aside from conventions and norms, the first priority is efficiency. So we have to understand their own underlying compilation.
The following will be used to analyze the opcode layer using PHP's extended VLD, with a focus on the OP number of OPS: and the system-level function call (OP)
1, first analysis define, in the PHP environment, create a file t.php, its code is as follows:
Define (' S ', 1);
Perform VLD command analysis opcode:
Where the OP number is 5, the operation is performed using Init_fcall, Send_val, Do_icall, RETURN 4 calls
2. Then analyze the const and modify the t.php code to:
Const S=1;
Perform vld named analysis opcode:
Where the OP number is 2, the operation is performed using the Declare_const, RETURN 2 calls
Obviously, the efficiency of the const far exceeds define!
Therefore , in the choice of const and define, it is advisable to use const, unless the constants that need to be defined are passed through the variable or are processed by means of define.
PHP constants define define and const