Const and define constants in php, but what are their specific differences? In fact, it is very simple to use const for class member variable definition. once defined and its value cannot be changed, define defines global constants and can access page d anywhere... const and define constants in php, but what are their specific differences? In fact, it is very simple to use const for class member variable definition. once defined and cannot change its value, define defines global constants, you can access the page anywhere. define cannot be defined in the class, but const can. The following is an article.
As we all know, define defines constants. what if we define constants in a class? Of course, define cannot be used, but const can be used, for example:
';}} Echo MyClass: CONSTANT .'
'; $ Classname = 'myclass'; echo $ classname: CONSTANT .'
'; // $ Class = new MyClass (); $ class-> showConstant (); echo $ class: CONSTANT.' after PHP 5.3.0 .'
'; // Print_r (get_defined_constants () after PHP 5.3.0; // you can use get_defined_constants () to obtain all defined constants.
Generally, define defines constants outside the class. const defines constants within the class, and const must be accessed by class name: variable name. However, php5.3 and above support defining constants outside the class through const, as shown in the following figure, it is OK:
const PHP_N = 'use const defined PHP'; echo PHP_N; if (defined('PHP_N')) { echo 'PHP_N is defined!'; }
Constants are generally named at an interval between upper-case words and underscores. constants must be defined as members of the class through const. we strongly recommend that you do not use global constants defined by define.
I will not talk about the basic knowledge of constants here, except for the above, other differences between define and const.
1. const cannot define constants in condition statements, but define is acceptable. the code is as follows:
2. const uses a normal constant name, and define can use an expression as the name. The code is as follows:
3. const can only accept static scalar, and define can use any expression. the code is as follows:
4. const itself is a language structure, and define is a function, so using const is much faster.
Constant naming rules:
A constant contains numbers, letters, and underscores. a number can be used as the constant name and separated by uppercase words and underscores. for example, EMBED_SUPPRESS_EMBED_EXCEPTION can be used, but EMBED_SUPPRESSEMBEDEXCEPTION is not allowed, the package name or class name of a constant is usually used as the prefix. for example, a constant in a Bug class should start with BUG _. a constant must be defined as a member of the class through "const, we strongly do not encourage the use of global constants defined by "define.