0
0
PHPprogramming~20 mins

Static properties and methods in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Static Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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;
?>
A1
B2
C0
DFatal error: Access to undeclared static property
Attempts:
2 left
💡 Hint
Static properties keep their value shared across all calls.
Predict Output
intermediate
2: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();
?>
ANothing, no output
BFatal error: Cannot call static method from instance
CLogging message
DWarning: Static method called non-statically
Attempts:
2 left
💡 Hint
In PHP, static methods can be called from instances but it's not recommended.
🔧 Debug
advanced
2: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();
?>
ANotice: Undefined property: Sample::$value
B10
CFatal error: Access to static property via non-static context
DWarning: Using $this to access static property
Attempts:
2 left
💡 Hint
Static properties must be accessed with self:: or ClassName:: inside methods.
📝 Syntax
advanced
2: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?
A
&lt;?php
class Test {
    public static $num = 5;
}
echo Test::$num;
?&gt;
B
&lt;?php
class Test {
    static $num = 5;
}
echo Test::$num;
?&gt;
C
&lt;?php
class Test {
    public static $num = 5
}
echo Test::$num;
?&gt;
D
&lt;?php
class Test {
    public static $num = 5;
}
echo Test-&gt;num;
?&gt;
Attempts:
2 left
💡 Hint
Check for missing semicolons and correct static property access syntax.
🚀 Application
expert
2: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();
?>
A2
B3
C1
DFatal error: Cannot call non-static method statically
Attempts:
2 left
💡 Hint
Check if the method add() is declared static or not before calling it statically.