Class constants with const
Learn to define class constants with the const keyword.
Defining a class constant with const
A class constant is a value bound to the class that cannot be changed (immutable). In PHP it is defined inside a class with the const keyword.
Constants differ from properties: there is no $ sign, the value cannot be reassigned after definition, and it is shared across all instances.
Example: class Circle { const PI = 3.14; }. Here PI is a class constant. We will cover access in the next lesson; for now we focus on definition.
Constant naming and type declaration
Class constant names are usually written in UPPER_CASE with underscores: MAX_SIZE, DEFAULT_TIMEOUT, HTTP_OK. This is a common naming convention.
In PHP 8.3 you can declare the type: const float PI = 3.14;. The type is optional but makes the code clearer.
A constant can be assigned a constant expression: a number, string, array, or another constant. But a variable ($x) is not allowed. Example: const array STATUS = ['active', 'passive']; is valid.
Exercise Circle class with a PI constant
Define a Circle class with a const float PI = 3.14; constant. Then print it with echo Circle::PI . "\n";. (The :: operator is explained in detail in the next lesson; for now we use it to print the constant.)
Show example solution
:PI . "\n";.
Example solution:
<?php
// Define a Circle class and the PI constant
class Circle {
const float PI = 3.14;
}
echo Circle::PI . "
";
Test yourself
-
Which keyword defines a class constant?
- function
- const
- static
- define
Show answer
const — Correct. The const keyword defines a constant inside a class.
-
Define a class constant
class Circle { ____ }Show answer
class Circle { const PI = 3.14; } -
Which is a valid class constant name?
- $MAX_RETRY
- max-retry-count
- MAX_RETRY_COUNT
- function MAX_RETRY
Show answer
MAX_RETRY_COUNT — Correct. MAX_RETRY_COUNT is a valid class constant name: no $, no dash.