![]() |
VOOZH | about |
In PHP, constants and magic constants are special identifiers that hold fixed values throughout script execution. They improve code clarity, reduce repetition, and help in debugging or configuration.
This guide covers everything you need to know, from defining constants to exploring the power of magic constants for debugging and performance.
PHP constants are like variables but with one key difference: their values cannot be changed once they are defined. They are used to store values that should remain consistent throughout the script, making your code more predictable.
You can define constants in PHP using two methods:
1. Using the define() function:
3.14159
2. Using the const keyword (used for class constants):
Constants can also be defined in classes using the const keyword:
For more details read the article - PHP Constants
Magic constants are predefined constants in PHP that change their value based on where they are used in the script. They help with debugging and logging information during script execution.
This constant returns the current line number in the file where it is used.
2
This constant gives the full path and name of the file being executed.
/home/guest/sandbox/Solution.php
Similar to __FILE__, but it returns the directory of the file being executed (without the filename).
/home/guest/sandbox
This constant returns the name of the function in which it is used.
myFunction
This constant gives the name of the class where it is used.
MyClass
This constant returns the name of the method where it is used.
MyClass::myMethod
This constant provides the current namespace.
MyNamespace
For more details read the article - PHP Magic Constants
PHP constants and magic constants serve different purposes in PHP programming. While both provide fixed values, their behavior and usage vary significantly.