@daniloparrajr

PHP Class Constants

  • 6/16/2024
  • 2 min read

Introduction

PHP constants are immutable meaning you can’t change their value once it is defined. PHP allows developers to associate constants per class with the default visibility of public.

Class constants can also be defined by a child class.

To define a class constant, use the const keyword followed by the constant property name and value. For constant’s property name, it is a standard practice to use uppercase and underscore’s for spacing.

class Status {
private const PAID = 'paid';
public const PENDING = 'pending';
}

Just like static properties or methods, class constants are allocated to the class itself and not to the class instance.

This means you can also access the class constants outside by using the scope resolution operator and inside using either the class name or the self keyword.

A class also have a built-in constant named class which resolves at compile time and returns a fully qualified class name.

namespace App\Modules;
class Status {
private const PAID = 'paid';
public const PENDING = 'pending';
public getPaidStatus() {
return self::PAID; // or Status::PAID
}
}
$transaction = new Transaction();
echo Status::PENDING; // pending
echo $transaction->getPaidStatus(); // paid
echo Status::class; // App\Modules\Status

Use-case of class constants

Single source of truth

If you have information that does not change, and you keep referencing it all over the code. It is better to move to a single class, this way if the time comes that you need to change the constant you just need to change it in one place.

Related Articles

PHP Traits

Learn how to reduce code duplication and improve code re-use using PHP Traits.

  • 7/16/2024
  • 3 min read