Challenge - 5 Problems
Class Constants Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of accessing class constant
What is the output of this PHP code?
PHP
<?php class Fruit { const NAME = 'Apple'; } echo Fruit::NAME;
Attempts:
2 left
💡 Hint
Class constants are accessed with :: operator.
✗ Incorrect
The constant NAME inside class Fruit is accessed using Fruit::NAME and outputs 'Apple'.
❓ Predict Output
intermediate2:00remaining
Output of constant in subclass
What will this code output?
PHP
<?php class Vehicle { const WHEELS = 4; } class Bike extends Vehicle { const WHEELS = 2; } echo Bike::WHEELS;
Attempts:
2 left
💡 Hint
Subclass constants can override parent constants.
✗ Incorrect
Bike class overrides WHEELS constant with 2, so Bike::WHEELS outputs 2.
❓ Predict Output
advanced2:00remaining
Output of accessing constant with self and static
What is the output of this PHP code?
PHP
<?php class ParentClass { const VALUE = 'Parent'; public static function showSelf() { echo self::VALUE; } public static function showStatic() { echo static::VALUE; } } class ChildClass extends ParentClass { const VALUE = 'Child'; } ChildClass::showSelf(); ChildClass::showStatic();
Attempts:
2 left
💡 Hint
self:: uses the class where method is defined; static:: uses called class.
✗ Incorrect
self::VALUE refers to ParentClass::VALUE ('Parent'), static::VALUE refers to ChildClass::VALUE ('Child').
❓ Predict Output
advanced2:00remaining
Output of accessing class constant via object
What will this code output?
PHP
<?php class Animal { const SOUND = 'Roar'; } $animal = new Animal(); echo $animal::SOUND;
Attempts:
2 left
💡 Hint
Since PHP 5.3, you can access constants via object with :: operator.
✗ Incorrect
Using $animal::SOUND accesses the constant SOUND of class Animal and outputs 'Roar'.
❓ Predict Output
expert2:00remaining
Output of constant expression with magic constant
What is the output of this PHP code?
PHP
<?php class Test { const FILE = __FILE__; public static function showFile() { echo self::FILE; } } Test::showFile();
Attempts:
2 left
💡 Hint
__FILE__ is a magic constant that gives the current file path.
✗ Incorrect
Class constant FILE is assigned the magic constant __FILE__, which contains the full path of the current file.