Challenge - 5 Problems
Final Mastery in PHP
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of final method call in subclass
What is the output of this PHP code?
PHP
<?php class Base { final public function greet() { echo "Hello from Base"; } } class Child extends Base { public function greet() { echo "Hello from Child"; } } $child = new Child(); $child->greet(); ?>
Attempts:
2 left
💡 Hint
Remember that final methods cannot be overridden in subclasses.
✗ Incorrect
The method greet() in Base is declared final, so Child cannot override it. Trying to do so causes a fatal error.
❓ Predict Output
intermediate2:00remaining
Output when instantiating a final class
What will this PHP code output?
PHP
<?php final class FinalClass { public function sayHi() { return "Hi!"; } } class SubClass extends FinalClass { } $obj = new SubClass(); echo $obj->sayHi(); ?>
Attempts:
2 left
💡 Hint
Final classes cannot be extended.
✗ Incorrect
FinalClass is declared final, so no class can extend it. Trying to extend causes a fatal error.
🔧 Debug
advanced2:00remaining
Identify the error in final method redeclaration
This PHP code causes an error. What is the error message?
PHP
<?php class ParentClass { final public function doSomething() { echo "Doing something"; } } class ChildClass extends ParentClass { public function doSomething() { echo "Doing something else"; } } ?>
Attempts:
2 left
💡 Hint
Final methods cannot be overridden in child classes.
✗ Incorrect
The child class tries to override a final method from the parent, which causes a fatal error.
🧠 Conceptual
advanced1:30remaining
Why use final classes or methods?
Which of the following is the best reason to declare a class or method as final in PHP?
Attempts:
2 left
💡 Hint
Think about controlling how code can be changed by others.
✗ Incorrect
Declaring a class or method final prevents other classes from changing its behavior by extending or overriding it, which helps maintain consistency and security.
❓ Predict Output
expert2:30remaining
Output of final method called via parent reference
What is the output of this PHP code?
PHP
<?php class A { final public function show() { echo "A"; } } class B extends A { public function show() { echo "B"; } } function callShow(A $obj) { $obj->show(); } $b = new B(); callShow($b); ?>
Attempts:
2 left
💡 Hint
Check if class B can override the final method show() from class A.
✗ Incorrect
Class B tries to override the final method show() from class A, which causes a fatal error before the function callShow is executed.