0
0
PHPprogramming~20 mins

Type declarations for parameters in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
PHP Type Declarations Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of function with typed parameters
What is the output of this PHP code when calling greet('Alice')?
PHP
<?php
function greet(string $name) {
    return "Hello, $name!";
}
echo greet('Alice');
AHello, Alice!
BHello, !
CTypeError
DFatal error
Attempts:
2 left
💡 Hint
The function expects a string parameter and returns a greeting.
Predict Output
intermediate
2:00remaining
Type error with wrong parameter type
What happens when this PHP code runs?
PHP
<?php
function square(int $num) {
    return $num * $num;
}
echo square('5');
A25
BTypeError
C5
DWarning: A non-numeric value encountered
Attempts:
2 left
💡 Hint
PHP can convert strings to integers automatically in some cases.
Predict Output
advanced
2:00remaining
Return type declaration with parameter types
What is the output of this PHP code?
PHP
<?php
function add(float $a, float $b): float {
    return $a + $b;
}
echo add(2, 3.5);
A5
BTypeError
C5.5
DFatal error
Attempts:
2 left
💡 Hint
PHP converts integers to floats when needed for float parameters.
Predict Output
advanced
2:00remaining
Nullable type declaration for parameter
What is the output of this PHP code?
PHP
<?php
function welcome(?string $name) {
    if ($name === null) {
        return 'Welcome, guest!';
    }
    return "Welcome, $name!";
}
echo welcome(null);
AFatal error
BWelcome, !
CTypeError
DWelcome, guest!
Attempts:
2 left
💡 Hint
The question mark before string means the parameter can be null.
Predict Output
expert
3:00remaining
Class type declaration for parameter
What is the output of this PHP code?
PHP
<?php
class User {
    public string $name;
    public function __construct(string $name) {
        $this->name = $name;
    }
}
function greetUser(User $user) {
    return "Hello, {$user->name}!";
}
$user = new User('Bob');
echo greetUser($user);
ATypeError
BHello, Bob!
CHello, !
DFatal error
Attempts:
2 left
💡 Hint
The function expects an object of class User.