0
0
PHPprogramming~10 mins

Static properties and methods in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to access the static property inside the class.

PHP
<?php
class Counter {
    public static $count = 0;
    public static function increment() {
        self::[1]++;
    }
}
Counter::increment();
echo Counter::$count;
Drag options to blanks, or click blank then click option'
Athis->count
Bself::$count
Ccount
D$count
Attempts:
3 left
💡 Hint
Common Mistakes
Using count (without $) after self:: treats it as a constant, causing an error.
Using this->count inside static method is invalid.
2fill in blank
medium

Complete the code to call the static method from outside the class.

PHP
<?php
class Logger {
    public static function log($msg) {
        echo $msg;
    }
}
Logger::[1]('Hello World');
Drag options to blanks, or click blank then click option'
Alog
Bwrite
Cecho
Dprint
Attempts:
3 left
💡 Hint
Common Mistakes
Using print or echo as method names causes errors.
Trying to call method with -> instead of ::.
3fill in blank
hard

Fix the error in accessing the static property inside the static method.

PHP
<?php
class User {
    public static $count = 0;
    public static function addUser() {
        [1]++;
    }
}
User::addUser();
echo User::$count;
Drag options to blanks, or click blank then click option'
Aself::$count
B$count
Cthis->count
DUser->count
Attempts:
3 left
💡 Hint
Common Mistakes
Using $count without self:: causes undefined variable error.
Using this->count inside static method causes error.
4fill in blank
hard

Fill both blanks to create a static method that returns the static property value.

PHP
<?php
class Config {
    public static $version = '1.0';
    public static function getVersion() {
        return [1]::[2];
    }
}
echo Config::getVersion();
Drag options to blanks, or click blank then click option'
Aself
BConfig
C$version
Dversion
Attempts:
3 left
💡 Hint
Common Mistakes
Using version (without $) after :: treats it as a constant, causing an error.
Using Config::version inside method is allowed but self::$version is preferred.
5fill in blank
hard

Fill all three blanks to define and use a static property and method that increments and returns the count.

PHP
<?php
class Visitor {
    public static [1] = 0;
    public static function [2]() {
        self::[1]++;
        return self::[1];
    }
}
echo Visitor::[2]();
Drag options to blanks, or click blank then click option'
A$count
Bincrement
Ccount
Dadd
Attempts:
3 left
💡 Hint
Common Mistakes
Using count (without $) in declaration or after self:: causes syntax or constant errors.
Using wrong method name causes call errors.