Challenge - 5 Problems
Strict Types Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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'; }
Attempts:
2 left
💡 Hint
With strict_types=1, PHP does not convert types automatically for function arguments.
✗ Incorrect
When strict_types is enabled, passing a string '10' to a function expecting int causes a TypeError. Without strict_types, PHP would convert '10' to int 10.
❓ Predict Output
intermediate2: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');
Attempts:
2 left
💡 Hint
Without strict_types, PHP converts scalar types automatically.
✗ Incorrect
Without strict_types, PHP converts the string '4' to integer 4 automatically, so the multiplication works and outputs 12.
❓ Predict Output
advanced2: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'; }
Attempts:
2 left
💡 Hint
Strict types also enforce return types, not just argument types.
✗ Incorrect
With strict_types=1, returning a string '5' from a function declared to return int causes a TypeError at runtime.
❓ Predict Output
advanced2: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'; }
Attempts:
2 left
💡 Hint
Method argument types are also strictly enforced with strict_types=1.
✗ Incorrect
Passing a string '3' to a method expecting int with strict_types=1 causes a TypeError.
🧠 Conceptual
expert2:00remaining
Understanding strict_types directive scope
Which statement about the
declare(strict_types=1); directive in PHP is TRUE?Attempts:
2 left
💡 Hint
Think about how PHP treats strict_types in separate files.
✗ Incorrect
The strict_types directive applies only to the file where it is declared. Included files must declare it separately to enforce strict typing.