PHP7 : Difference between define() vs const()

As of PHP 5.3 there are two ways to define constants: Either using the const keyword or using the define() function:
1 2 |
const FOO = 'BAR'; define('FOO', 'BAR'); |
The fundamental difference between those two ways is that const defines constants at compile time, whereas define defines them at run time.
If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string (CONSTANT vs “CONSTANT”). This fallback is deprecated as of PHP 7.2.0, and an error of level E_WARNING is issued when it happens (previously, an error of level E_NOTICE has been issued instead.) See also the manual entry on why $foo[bar] is wrong (unless you first define() bar as a constant). This does not apply to (fully) qualified constants, which will raise a fatal error if undefined. If you simply want to check if a constant is set, use the defined() function.
{Read:- 5 Ways to Improve SEO on Your WordPress Site }
Disadvantages of const are:
- Constants do not have a dollar sign ($) before them;
- Prior to PHP 5.3, Constants may only be defined using the define() function, not by simple assignment;
- Constants may be defined and accessed anywhere without regard to variable scoping rules;
- Constants may not be redefined or undefined once they have been set; and
- Constants may only evaluate to scalar values. As of PHP 5.6 it is possible to define array constant using constkeywords and as of PHP 7 array constants can also be defined using define() You may use arrays in constant scalar expressions (for example, const FOO = array(1,2,3)[0];), but the end result must be a value of allowed type.
Example #1
1 2 3 4 5 |
<?php define("CONSTANT", "Hello world."); echo CONSTANT; // outputs "Hello world." echo Constant; // outputs "Constant" and issues a notice. ?> |
Example #2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php // Works as of PHP 5.3.0 const CONSTANT = 'Hello World'; echo CONSTANT; // Works as of PHP 5.6.0 const ANOTHER_CONST = CONSTANT.'; Goodbye World'; echo ANOTHER_CONST; const ANIMALS = array('dog', 'cat', 'bird'); echo ANIMALS[1]; // outputs "cat" // Works as of PHP 7 define('ANIMALS', array( 'dog', 'cat', 'bird' )); echo ANIMALS[1]; // outputs "cat" ?> |
Unless you need any type of conditional or expressional definition, use const
s instead of define()
{Read:- How to Build a WordPress Site in 1 Day }