define() is the function used in PHP to define constants. Its syntax is very simple:
define('CONSTANT_NAME', 'value');
This function sets the value of the constant CONSTANT_NAME to 'value', and once defined, the constant’s value cannot be changed.
However, if we accidentally call define() multiple times in the code to define a constant with the same name, PHP will throw an error:
Notice: Constant CONSTANT_NAME already defined
defined() is used to check whether a constant has already been defined. Its syntax is:
defined('CONSTANT_NAME');
If the constant has been defined, defined() returns true; otherwise, it returns false.
To avoid errors caused by redefining constants, we can combine define() and defined(). Specifically, before defining a constant, first use defined() to check if the constant already exists. Only if the constant is not defined do we use define() to define it.
<?php
<p>if (!defined('MY_CONSTANT')) {<br>
define('MY_CONSTANT', 'SomeValue');<br>
}</p>
<p>echo MY_CONSTANT; // Output: SomeValue</p>
<p>?><br>
In the code above, defined('MY_CONSTANT') first checks whether MY_CONSTANT is defined. If not, it then uses define() to define the constant.
This approach is very practical in many cases, especially when using external libraries or frameworks, where constant redefinition issues often occur. For example, when including multiple PHP files that might all attempt to define the same constant, if none of the files check whether the constant is already defined, including these files can cause redefinition errors.
By combining defined() and define(), we ensure that the same constant is defined only once, thus avoiding unnecessary errors.
Suppose we have two files, file1.php and file2.php, both trying to define the same constant SITE_URL. Without using defined() to check if the constant is already defined, this would lead to errors.
<?php
<p>if (!defined('SITE_URL')) {<br>
define('SITE_URL', '<a rel="noopener" target="_new" class="" href="https://m66.net">https://m66.net</a>');<br>
}</p>
<p>?><br>
<?php
<p>if (!defined('SITE_URL')) {<br>
define('SITE_URL', '<a rel="noopener" target="_new" class="" href="https://m66.net">https://m66.net</a>');<br>
}</p>
<p>?><br>
With this approach, although both files define SITE_URL, the use of defined() prevents duplicate definitions. Therefore, including both files will not cause constant redefinition errors.