CodeBlanks Logo Icon CodeBlanks

Summary - Class constants

PHP course · Intermediate · Lesson 41/115

Build an order class with status constants using const, :: and ::class.

Summary - Class constants

In this group you learned class constants:

  • const defines a class constant; no $ sign, immutable.
  • The :: operator reaches constants from outside with ClassName::CONSTANT and from inside with self::CONSTANT.
  • ::class returns the fully qualified class name as a string.
  • Constants are immutable; static properties can change.
  • Great for configuration, status codes and enum-like structures.

Now you'll combine these in an Order class with status constants.

Exercise Order class with status constants

Define an Order class with const string PENDING = 'pending'; and const string SHIPPED = 'shipped';. Add a private string $status property and a public function __construct(string $status = self::PENDING) that assigns $this->status = $status. Add public function label(): string with if ($this->status === self::SHIPPED) { return 'Shipped'; } and a final return 'Pending'. Then create $order = new Order(Order::SHIPPED) and print echo $order->label() . "\n". (Expected output: Shipped)

Show example solution
:PENDING) { $this->status = $status; } public function label(): string { if ($this->status === self::SHIPPED) { return 'Shipped'; } return 'Pending'; } } then $order = new Order(Order::SHIPPED); echo $order->label() . "\n";
Example solution:
<?php
// Define an Order class
class Order {
    const string PENDING = 'pending';
    const string SHIPPED = 'shipped';
    private string $status;
    public function __construct(string $status = self::PENDING) {
        $this->status = $status;
    }
    public function label(): string {
        if ($this->status === self::SHIPPED) {
            return 'Shipped';
        }
        return 'Pending';
    }
}
$order = new Order(Order::SHIPPED);
echo $order->label() . "
";

Tips for class constants

In summary: use const for immutable values and static for mutable ones. Access constants with ::; self:: inside, ClassName:: outside.

Use constants for configuration, status codes and enum-like structures. This makes your code more readable and safe; it avoids the magic number and magic string problems.

In the next group you'll learn to define contracts between classes with interfaces.

Test yourself

  1. Match the class constant concepts

    const
    Defines a class constant
    ::
    Operator to access constants
    ::class
    Gives the fully qualified name
    self::
    In-class access
  2. For order status in an e-commerce app, what is the best choice?

    • Statuses defined as class constants (const)
    • A separate variable for each order
    • Writing a new string in the database each time
    • Storing it as a public property
    Show answer

    Statuses defined as class constants (const) — Correct. Order statuses are immutable values; a class constant is ideal.

All lessons in Intermediate