0
0
PHPprogramming~10 mins

Constants in classes in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Constants in classes
Define class with constant
Access constant via ClassName::CONSTANT
Use constant value in code
Output or use constant value
End
This flow shows how a class constant is defined, accessed using ClassName::CONSTANT, and then used in the program.
Execution Sample
PHP
<?php
class Car {
  const WHEELS = 4;
}
echo Car::WHEELS;
?>
Defines a class Car with a constant WHEELS and prints its value.
Execution Table
StepActionCode LineEvaluationOutput
1Define class Car with constant WHEELS=4class Car { const WHEELS = 4; }Class Car created with constant WHEELS=4
2Access constant WHEELS from CarCar::WHEELSValue 4 retrieved
3Print constant valueecho Car::WHEELS;Output 44
4End of script
💡 Script ends after printing the constant value 4.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
Car::WHEELSundefined4444
Key Moments - 2 Insights
Why do we use ClassName::CONSTANT instead of $this->CONSTANT?
Class constants are accessed with ClassName::CONSTANT because they belong to the class itself, not to an instance. This is shown in execution_table step 2 where Car::WHEELS is used.
Can we change the value of a class constant after defining it?
No, class constants cannot be changed after definition. The execution_table shows the constant value stays 4 throughout.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of Car::WHEELS at step 2?
Anull
Bundefined
C4
D0
💡 Hint
Check the 'Evaluation' column at step 2 in the execution_table.
At which step does the program output the constant value?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look for the 'Output' column in the execution_table.
If we tried to change Car::WHEELS after definition, what would happen?
AThe value changes successfully
BThe value remains unchanged
CA syntax error occurs
DThe program outputs the new value
💡 Hint
Refer to key_moments about immutability of class constants.
Concept Snapshot
Class constants are fixed values inside a class.
Define with 'const NAME = value;'.
Access with ClassName::NAME.
Cannot be changed after definition.
Useful for fixed data related to the class.
Full Transcript
This example shows how to define and use constants inside PHP classes. We define a class Car with a constant WHEELS set to 4. We access this constant using Car::WHEELS and print its value. Class constants belong to the class itself, not instances, so we use :: to access them. Constants cannot be changed after they are set. The execution table traces each step from defining the class, accessing the constant, printing it, and ending the script. Key moments clarify why we use ClassName::CONSTANT and that constants are immutable. The quiz tests understanding of these points.