Challenge - 5 Problems
Static Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of accessing static property inside class
What is the output of this PHP code?
PHP
<?php class Counter { public static $count = 0; public static function increment() { self::$count++; } } Counter::increment(); Counter::increment(); echo Counter::$count; ?>
Attempts:
2 left
💡 Hint
Static properties keep their value shared across all calls.
✗ Incorrect
The static property $count starts at 0. Each call to increment() increases it by 1. After two calls, $count is 2.
❓ Predict Output
intermediate2:00remaining
Output of static method called from instance
What will this PHP code output?
PHP
<?php class Logger { public static function log() { echo "Logging message"; } } $log = new Logger(); $log->log(); ?>
Attempts:
2 left
💡 Hint
In PHP, static methods can be called from instances but it's not recommended.
✗ Incorrect
PHP allows calling static methods from an instance, so it outputs the string.
🔧 Debug
advanced2:00remaining
Identify the error in static property access
What error will this PHP code produce?
PHP
<?php class Sample { public static $value = 10; public function show() { echo $this->value; } } $obj = new Sample(); $obj->show(); ?>
Attempts:
2 left
💡 Hint
Static properties must be accessed with self:: or ClassName:: inside methods.
✗ Incorrect
Using $this->value tries to access an instance property, but $value is static, so PHP raises a notice about undefined property.
📝 Syntax
advanced2:00remaining
Which option correctly defines and accesses a static property?
Which of the following PHP code snippets will run without syntax errors and output 5?
Attempts:
2 left
💡 Hint
Check for missing semicolons and correct static property access syntax.
✗ Incorrect
Option A correctly declares a public static property with a semicolon and accesses it with ClassName::$property. Option A misses 'public' but is valid in PHP 7+, but to keep one correct answer, we choose A. Option A misses semicolon causing syntax error. Option A uses wrong access syntax.
🚀 Application
expert2:00remaining
How many times is the static property incremented?
Consider this PHP code. How many times will the static property $counter be incremented after running all lines?
PHP
<?php class Incrementer { public static $counter = 0; public function add() { self::$counter++; } } $a = new Incrementer(); $b = new Incrementer(); $a->add(); $b->add(); Incrementer::add(); ?>
Attempts:
2 left
💡 Hint
Check if the method add() is declared static or not before calling it statically.
✗ Incorrect
The method add() is not declared static, so calling Incrementer::add() causes a fatal error.