How to define a specific variable in your program to have a fixed value that cannot be mutated or changed in PHP

1. Constants using define():
  • Definition: define(name, value, case_insensitive)
  • Description: Creates a global constant with a fixed value.

 
define('PI', 3.14159);
// Accessing the constant:
echo PI; // Output: 3.14159
 

2. Class Constants using const keyword:
  • Definition: const name = value; (within a class)
  • Description: Creates a constant accessible only within the class and its instances.

 
class Circle {
    const PI = 3.14159;
 
    public function getArea($radius) {
        return self::PI * $radius * $radius;
    }
}
 
// Accessing the constant:
echo Circle::PI; // Output: 3.14159
 
 

3. Readonly Properties (PHP 8.1+):
  • Definition: class MyClass { public readonly property $name = value; }
  • Description: Declares a property that can only be set during object initialization.

 
class User {
    public readonly string $id = '12345';
}
 
$user = new User();
$user->id = '98765'; // Error: Cannot modify readonly property
 
 

4. Getter Methods:
  • Description: Create a method to access a value without directly exposing a mutable variable.

 
class Config {
    private $apiKey = 'your_api_key';
 
    public function getApiKey() {
        return $this->apiKey;
    }
}
 
$config = new Config();
$apiKey = $config->getApiKey();
echo $apiKey; //  your_api_key