Constants in PHP are similar to variables, except that once they are defined, they cannot be changed or undefined during the script's execution. Here's what you need to know about PHP constants:
To define a constant, you use the define() function:
define("CONSTANT_NAME", "Value");
For instance:
define("PI", 3.14159265359);
echo PI; // Outputs: 3.14159265359
Case-Sensitivity: By default, constant names are case-sensitive. However, you can define case-insensitive constants by providing a third parameter as true:
define("CASE_INSENSITIVE", "Hello, World!", true);
echo case_insensitive; // Outputs: Hello, World!
Global Scope: Constants have a global scope, meaning they can be accessed anywhere in your script without concern for variable scope rules.
No Dollar Sign: Unlike variables, constants are not preceded by the $ sign.
Another way to define constants, especially in the context of object-oriented programming, is by using the const keyword:
class Circle {
const PI = 3.14159265359;
public function getArea($radius) {
return self::PI * $radius * $radius;
}
}
Using const is mainly for class constants, but it can also be used outside of a class in global scope.
Checking If a Constant Exists: You can check if a constant has been defined using the defined() function:
if (defined("PI")) {
echo PI; // Outputs: 3.14159265359
}
Getting All Defined Constants: The get_defined_constants() function returns an associative array with all the constants that have been defined:
print_r(get_defined_constants());
This will include both user-defined constants and constants from PHP's core and extensions.
PHP provides a set of special constants called "magic constants" that change depending on where they're used. The most well-known of these is __FILE__, which returns the full path and filename of the file it's used in. Others include:
Constants, with their unchanging nature, are particularly useful for values that you want to remain consistent throughout your application, like configuration settings, API keys, mathematical values, and more.
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here