Home > Article > Backend Development > What is the difference between define and const in php?
Difference: 1. const is used for the definition of class member variables, while define cannot be used for the definition of class member variables; 2. const only accepts static scalars, while define can use any expression; 3. const Defining constants is case-sensitive, but define can specify whether it is case-sensitive through the third parameter.
Constants are case-sensitive by default. Usually, constant identifiers are always uppercase.
You can use the define()
function to define constants. After php5.3.0, you can use the const
keyword to define constants outside the class definition. In previous versions, the const keyword could only be used within classes.
Constant can only contain scalar data (boolean, integer, float, string). Resource constants can be defined, but should be avoided.
Define constants
define("PI", 3.14); echo PI; // 3.14 echo pi; // 输出 "pi" 并发出一个Warning信息 // 以下代码在 PHP 5.3.0 后可以正常工作 const RATE = 'Hello World'; echo RATE;
When defining constants in PHP, the difference between const and define
1. Const itself is A language structure, while define is a function.
2. Const is much faster than define during compilation
3. Const is used for the definition of class member variables, but define cannot be used for the definition of class member variables
4. const cannot be used in conditional statements
if (...){ const FOO = 'BAR'; // 无效的 } if (...) { define('FOO', 'BAR'); // 有效的 }
5. const only accepts static scalars, while define can use any expression
const BIT_5 = 1 << 5; // 无效的 define('BIT_5', 1 << 5); // 有效的
6. const is case-sensitive when defining constants, but define can specify whether case sensitivity is through the third parameter (true indicates case insensitivity)
define('FOO', 'BAR', true); echo FOO; // BAR echo foo; // BAR
Dynamic constant name
If the constant name is dynamic, you can also use the function constant() to get the value of the constant. Use get_defined_contstants() to get a list of all defined constants.
define('PI',3.14); $chang = 'PI'; echo $chang,'<br/>'; // PI echo constant($chang); // 3.14
defined — Check whether a constant with a certain name exists
// 真实开发一般是这样的 if(!defined('HEI')){ define('HEI',8846); }
Recommended related tutorials: "PHP Tutorial"
The above is the detailed content of What is the difference between define and const in php?. For more information, please follow other related articles on the PHP Chinese website!