0
0
PHPprogramming~20 mins

Declare strict_types directive in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Strict Types Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output with strict_types enabled
What is the output of this PHP code when declare(strict_types=1); is used?
PHP
<?php

declare(strict_types=1);

function addInts(int $a, int $b): int {
    return $a + $b;
}

try {
    echo addInts(5, '10');
} catch (TypeError $e) {
    echo 'TypeError caught';
}
A15
BTypeError caught
C5
D10
Attempts:
2 left
💡 Hint
With strict_types=1, PHP does not convert types automatically for function arguments.
Predict Output
intermediate
2:00remaining
Behavior without strict_types directive
What will this PHP code output when declare(strict_types=1); is NOT present?
PHP
<?php

function multiplyInts(int $x, int $y): int {
    return $x * $y;
}

echo multiplyInts(3, '4');
A12
BTypeError caught
C7
D34
Attempts:
2 left
💡 Hint
Without strict_types, PHP converts scalar types automatically.
Predict Output
advanced
2:00remaining
Return type enforcement with strict_types
What is the output of this PHP code with declare(strict_types=1);?
PHP
<?php

declare(strict_types=1);

function getNumber(): int {
    return '5';
}

try {
    echo getNumber();
} catch (TypeError $e) {
    echo 'Return type error';
}
A0
BTypeError caught
C5
DReturn type error
Attempts:
2 left
💡 Hint
Strict types also enforce return types, not just argument types.
Predict Output
advanced
2:00remaining
Effect of strict_types on scalar type coercion in method calls
Given this PHP code with declare(strict_types=1);, what will be the output?
PHP
<?php

declare(strict_types=1);

class Calculator {
    public function subtract(int $a, int $b): int {
        return $a - $b;
    }
}

$calc = new Calculator();
try {
    echo $calc->subtract(10, '3');
} catch (TypeError $e) {
    echo 'TypeError caught';
}
ATypeError caught
B103
C7
D13
Attempts:
2 left
💡 Hint
Method argument types are also strictly enforced with strict_types=1.
🧠 Conceptual
expert
2:00remaining
Understanding strict_types directive scope
Which statement about the declare(strict_types=1); directive in PHP is TRUE?
AIt disables all type checking for scalar types in the file where declared.
BIt enforces strict typing globally across all included files regardless of their own declarations.
CIt only affects the file where it is declared and does not affect included or required files.
DIt automatically converts all scalar types to the expected type without error.
Attempts:
2 left
💡 Hint
Think about how PHP treats strict_types in separate files.