0
0
PHPprogramming~20 mins

Constants in classes in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Class Constants Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of accessing class constant
What is the output of this PHP code?
PHP
<?php
class Fruit {
    const NAME = 'Apple';
}
echo Fruit::NAME;
ANAME
BApple
CError: Cannot access constant
Dnull
Attempts:
2 left
💡 Hint
Class constants are accessed with :: operator.
Predict Output
intermediate
2: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;
A2
Bnull
CError: Cannot override constant
D4
Attempts:
2 left
💡 Hint
Subclass constants can override parent constants.
Predict Output
advanced
2: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();
AChildParent
BChildChild
CParentParent
DParentChild
Attempts:
2 left
💡 Hint
self:: uses the class where method is defined; static:: uses called class.
Predict Output
advanced
2: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;
ARoar
BError: Cannot access constant via object
CSOUND
Dnull
Attempts:
2 left
💡 Hint
Since PHP 5.3, you can access constants via object with :: operator.
Predict Output
expert
2: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();
AError: Cannot use magic constant in class constant
B__FILE__
CThe full path and filename of the file where this code is saved
Dnull
Attempts:
2 left
💡 Hint
__FILE__ is a magic constant that gives the current file path.