In PHP, constants are similar to variables, but their value cannot be changed once they are defined. Constants are useful for storing values that are known and unlikely to change during the execution of a script. Constants are defined using the define() function, which takes two arguments: the name of the constant and its value. Here’s an example:
define("PI", 3.14);
echo PI; // output: 3.14
In this example, we define a constant named “PI” with a value of 3.14 using the define() function. We then use the constant in our code by simply referring to it by name.
Constants in PHP follow the same scoping rules as variables. They can be defined and accessed globally, or within a function or class. When defining a constant, you should give it a meaningful name that reflects its purpose and use uppercase letters to make it stand out from variables.
const MAX_SIZE = 1024;
echo MAX_SIZE; // output: 1024
In PHP 5.3 and later versions, you can also define constants using the const keyword:
const PI = 3.14;
echo PI; // output: 3.14
Constants can also be used within classes and objects. To define a class constant, you need to use the const keyword and define the constant inside the class. To access the constant, you use the :: operator. Here’s an example:
class Circle {
const PI = 3.14;
public function getArea($radius) {
return self::PI * $radius * $radius;
}
}
$circle = new Circle();
echo $circle->getArea(5); // output: 78.5
In this example, we define a class named “Circle” with a constant PI and a method getArea() that calculates the area of a circle. We use the self keyword to access the class constant inside the method.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.