0
0
PHPprogramming~20 mins

Class declaration syntax in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
PHP Class Syntax Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple PHP class method call
What is the output of this PHP code?
PHP
<?php
class Greeting {
    public function sayHello() {
        return "Hello, world!";
    }
}
$greet = new Greeting();
echo $greet->sayHello();
?>
AParse error: syntax error, unexpected 'return'
BHello, world!
CFatal error: Call to undefined method Greeting::sayHello()
DHello world
Attempts:
2 left
💡 Hint
Look at the method name and how it is called on the object.
Predict Output
intermediate
2:00remaining
Output when accessing a private property directly
What happens when this PHP code runs?
PHP
<?php
class Person {
    private string $name = "Alice";
}
$p = new Person();
echo $p->name;
?>
AAlice
BNotice: Undefined property: Person::$name
CFatal error: Uncaught Error: Cannot access private property Person::$name
DParse error: syntax error, unexpected 'string'
Attempts:
2 left
💡 Hint
Check the visibility of the property and how it is accessed.
🔧 Debug
advanced
2:00remaining
Identify the syntax error in this class declaration
This PHP code has a syntax error. Which option shows the exact error message produced when running it?
PHP
<?php
class Car {
    public $make;
    public $model
    public function __construct($make, $model) {
        $this->make = $make;
        $this->model = $model;
    }
}
?>
AParse error: syntax error, unexpected 'public' (T_PUBLIC) in line 4
BFatal error: Cannot redeclare class Car
CNotice: Undefined variable: model
DParse error: syntax error, unexpected '$make' (T_VARIABLE) in line 5
Attempts:
2 left
💡 Hint
Look carefully at the property declarations and missing punctuation.
Predict Output
advanced
2:00remaining
Output of static property access in PHP class
What is the output of this PHP code?
PHP
<?php
class Counter {
    public static int $count = 0;
    public function __construct() {
        self::$count++;
    }
}
new Counter();
new Counter();
echo Counter::$count;
?>
A1
B0
CFatal error: Access to undeclared static property Counter::$count
D2
Attempts:
2 left
💡 Hint
Static properties are shared across all instances of the class.
Predict Output
expert
2:00remaining
Output of class constant and method call
What is the output of this PHP code?
PHP
<?php
class MathConstants {
    public const PI = 3.14;
    public static function getPi() {
        return self::PI;
    }
}
echo MathConstants::PI . ' ' . MathConstants::getPi();
?>
A3.14 3.14
BPI 3.14
C3.14 getPi
DFatal error: Access to undefined constant PI
Attempts:
2 left
💡 Hint
Class constants are accessed with :: and can be used inside static methods with self::