Lesson contents

PHP — Named constants with const

A PHP constant gives a fixed value a name without a dollar sign. A constant expression can use constants declared earlier.

A simple example

Use a fixed value

  1. Start with Unit is 3
  2. Do this Multiply by 2
  3. Result 6
Give 3 a name and reuse that name in the multiplication.
lesson.php
<?php
const UNIT = 3;
echo 2 * UNIT, PHP_EOL;
Output
6
Advertisements

Name a fixed scheduling interval

Express a 30-minute slot in terms of a 15-minute base interval. Keep the slot count separate so different bookings can reuse the same rule. Define the scheduling rule once, then use a variable for the booking. A later booking can use a different slot count without changing the interval.

Length of a slot: 30 minutes. Rehearsal: 3 slots. Time reserved: 90 minutes.
Reserve a rehearsal room

The music room can be booked in 30-minute slots. A rehearsal needs three slots, so the calendar sets aside 90 minutes. Naming the slot length lets every booking use the same rule.

Run the example

Use PHP 8.2 or later. Run these commands from the directory containing the example.

php lesson.php
lesson.php
<?php
declare(strict_types=1);

const BASE_MINUTES = 15;
const SLOT_MINUTES = 2 * BASE_MINUTES;
$bookedSlots = 3;
printf("%d minutes\n", $bookedSlots * SLOT_MINUTES);
Output
90 minutes

Two base intervals make each slot 30 minutes. A booking of three slots lasts 90 minutes.

Try it yourself

If the base interval changes to 10 minutes, how long is the same three-slot booking?

Check your answer

Each slot now lasts 20 minutes, so the booking lasts 60 minutes.

PHP language manual

Related tags

  • PHP
  • constants
  • bindings
  • configuration