Skip to content

Chapter 5 of 38

Constants

Define global, class, magic, and enum-like immutable values safely.

26 minutes 10 quick checksBy Subha Prasad
Lesson 5 of 38Course navigation

Lesson content

Read, practise, then check your understanding

Constants name values that should not be reassigned. Prefer const declarations; define supports runtime names. Class constants group facts with a type, while magic constants depend on source context.

Practical example

<?php
const APP_NAME = 'Learning Portal';
final class Limits { public const MAX_UPLOAD_BYTES = 5_000_000; }
$root = __DIR__;
$className = Limits::class;

Use enums for closed domain sets and deployment configuration for environment-dependent values. Never commit secrets as constants. Magic constants such as __FILE__, __DIR__, and __METHOD__ are useful for diagnostics and relative paths.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes const?
Which PHP term matches this description: A compile-time-style declaration for a named immutable value.
Which statement best describes define?
Which PHP term matches this description: A function defining a constant at runtime.
Which statement best describes class constant?
Which PHP term matches this description: A constant scoped to a class/interface/trait/enum.
Which statement best describes magic constant?
Which PHP term matches this description: A context-sensitive constant such as __FILE__ or __DIR__.
Which statement best describes ::class?
Which PHP term matches this description: A compile-time fully qualified class-name string.

0 of 10 checks passed

Your progress is saved on this device.