PHP OOP – Class Constants

Welcome to The Coding College! In this tutorial, we’ll discuss class constants in PHP Object-Oriented Programming (OOP). Class constants are fixed values that cannot be changed during script execution, making them ideal for values that remain constant throughout the life of the class.

What are Class Constants?

A class constant is a value that:

  • Is defined in a class using the const keyword.
  • Cannot be modified once declared.
  • Is accessed directly without creating an object, using the scope resolution operator (::).

Syntax for Class Constants

Here’s the basic syntax for defining and accessing class constants:

<?php
class ClassName {
    const CONSTANT_NAME = "Constant Value"; // Declare a constant
}

// Access the constant
echo ClassName::CONSTANT_NAME;
?>

Example: Declaring and Accessing Class Constants

<?php
class Car {
    const WHEELS = 4; // Define a constant

    public function showWheels() {
        return self::WHEELS; // Access constant using self::
    }
}

// Access the constant directly through the class
echo "Number of wheels: " . Car::WHEELS . "<br>"; // Output: 4

// Access the constant through an object
$car = new Car();
echo "Number of wheels: " . $car->showWheels(); // Output: 4
?>

Explanation:

  1. Direct Access: Constants are accessed using the class name and the :: operator (e.g., Car::WHEELS).
  2. Inside the Class: Use self:: to refer to the constant within the same class.

Properties of Class Constants

  1. Immutability: Class constants cannot be changed once declared.
  2. No $ Sign: Unlike variables, constants do not use the $ sign.
  3. Static by Nature: Constants belong to the class, not any specific object.
  4. Case Sensitivity: Class constants are case-sensitive by default.

Using Class Constants in Inheritance

Class constants are inherited by child classes but can also be overridden in the child class.

Example: Inheriting and Overriding Class Constants

<?php
class ParentClass {
    const GREETING = "Hello from Parent!";
}

class ChildClass extends ParentClass {
    const GREETING = "Hello from Child!"; // Override parent constant
}

echo ParentClass::GREETING . "<br>"; // Output: Hello from Parent!
echo ChildClass::GREETING . "<br>";  // Output: Hello from Child!
?>

Accessing Parent Class Constants

If the child class overrides the constant, you can still access the parent class’s constant using the parent:: keyword.

<?php
class ParentClass {
    const GREETING = "Hello from Parent!";
}

class ChildClass extends ParentClass {
    const GREETING = "Hello from Child!";

    public function showParentGreeting() {
        return parent::GREETING; // Access parent constant
    }
}

$child = new ChildClass();
echo $child->showParentGreeting(); // Output: Hello from Parent!
?>

Real-World Example: Class Constants

Let’s look at a practical example where constants are used to define fixed values, such as tax rates or error codes.

Example: Defining Tax Rates

<?php
class Tax {
    const TAX_RATE = 0.18; // Tax rate as a constant

    public function calculateTax($amount) {
        return $amount * self::TAX_RATE; // Use the constant
    }
}

$tax = new Tax();
echo "Tax on $100: $" . $tax->calculateTax(100); // Output: Tax on $100: $18
?>

Example: Error Codes

<?php
class ErrorCodes {
    const NOT_FOUND = 404;
    const FORBIDDEN = 403;
    const SERVER_ERROR = 500;
}

echo "Error: " . ErrorCodes::NOT_FOUND; // Output: Error: 404
?>

Using Class Constants with Static Methods

Class constants are often used alongside static methods to define reusable configurations or behavior.

Example: Static Methods with Constants

<?php
class AppConfig {
    const APP_NAME = "The Coding College";
    const VERSION = "1.0.0";

    public static function getAppDetails() {
        return self::APP_NAME . " - Version " . self::VERSION;
    }
}

echo AppConfig::getAppDetails(); // Output: The Coding College - Version 1.0.0
?>

final Keyword with Class Constants

You can declare a class as final to prevent inheritance, ensuring the constants defined in the class remain unaltered.

<?php
final class Config {
    const DB_HOST = "localhost";
    const DB_USER = "root";
    const DB_PASS = "password";
}

// The following will cause an error:
// class ExtendedConfig extends Config {}
?>

Differences Between const and define()

Featureconstdefine()
UsageInside classesOutside classes
ScopeClass scopeGlobal scope
EvaluationCompile-time constantRuntime constant
InheritanceCan be inheritedNot applicable

Best Practices for Using Class Constants

  1. Use for Fixed Values: Define constants for values that remain unchanged, like configuration settings or app constants.
  2. Name in Uppercase: Follow the convention of naming constants in uppercase (e.g., DB_HOST).
  3. Avoid Overloading: Do not define constants for values that are likely to change frequently.

Conclusion

Class constants in PHP OOP are a great way to define fixed, unchangeable values that are associated with a class. They improve readability, maintainability, and make your code more structured.

To learn more about PHP OOP concepts and practical applications, visit The Coding College.

Leave a Comment