51 lines
1.7 KiB
Plaintext
51 lines
1.7 KiB
Plaintext
== Why is this an issue?
|
|
|
|
In PHP, the `define` function allows you to define a named constant with a specific value, which cannot be changed later in the code.
|
|
Once a constant has been defined, it can be used throughout the entire script, including in function and class definitions.
|
|
|
|
Assigning a value to the same constant name using two or more `define` statements does not cause PHP to fail.
|
|
In such a case, PHP only issues a warning and ignores the second and further `define`.
|
|
|
|
=== What is the potential impact?
|
|
|
|
Using duplicate define statements can lead to unnecessary code that can be safely removed in the best case scenario.
|
|
|
|
It is important to note that in the worst case, duplicate define statements may assign different values, which can result in hard-to-debug issues when other parts of the code make incorrect assumptions about the constant's value.
|
|
|
|
It is advisable to avoid duplicate define statements to prevent potential unexpected behavior and to ensure code clarity and correctness.
|
|
|
|
== How to fix it
|
|
|
|
Remove duplicate `define` statements and only keep the intended one.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,php,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
define( 'CONSTANT_VALUE', 'old value' );
|
|
define( 'SCRIPT_DEBUG', 1 );
|
|
|
|
// Noncompliant, tries to redefine constant defined 2 lines above
|
|
define( 'CONSTANT_VALUE', 'intended value' );
|
|
echo CONSTANT_VALUE; // output: 'old value'
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,php,diff-id=1,diff-type=compliant]
|
|
----
|
|
define( 'SCRIPT_DEBUG', 1 );
|
|
|
|
// Compliant
|
|
define( 'CONSTANT_VALUE', 'intended value' );
|
|
echo CONSTANT_VALUE; // output: 'intended value'
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://www.php.net/manual/en/language.constants.syntax.php[PHP Manual - Constants Syntax]
|