Recall & Review
beginner
What does the
declare(strict_types=1); directive do in PHP?It enforces strict type checking for scalar type declarations in the file, meaning PHP will not perform type coercion and will throw a TypeError if types do not match exactly.
Click to reveal answer
beginner
Where must the
declare(strict_types=1); directive be placed in a PHP file?It must be the very first statement in the PHP file, immediately after the opening
<?php tag, before any other code or whitespace.Click to reveal answer
intermediate
True or False: The
strict_types directive affects all files included or required by the current PHP file.False. The
strict_types directive applies only to the file where it is declared. Each file must declare it separately if strict typing is desired.Click to reveal answer
beginner
What happens if you call a function with a type mismatch when
strict_types=1 is declared?PHP throws a
TypeError exception immediately instead of trying to convert the value to the expected type.Click to reveal answer
beginner
Example: How to declare strict types in a PHP file?
Place this at the top of your PHP file:<br>
<?php declare(strict_types=1); // Your code here
Click to reveal answer
What is the correct way to enable strict typing in a PHP file?
✗ Incorrect
The
declare(strict_types=1); directive must be the first statement in the PHP file to enable strict typing.If
strict_types=1 is declared, what happens when you pass a float to a function expecting an int?✗ Incorrect
With strict types enabled, PHP throws a TypeError if the argument type does not exactly match the declared type.
Does the
strict_types directive affect included or required files automatically?✗ Incorrect
Strict typing applies only to the file where
declare(strict_types=1); is set.Where must the
declare(strict_types=1); statement appear in a PHP file?✗ Incorrect
It must be the very first statement after the opening PHP tag, before any other code.
What is the default behavior if
strict_types is not declared?✗ Incorrect
By default, PHP uses weak typing and converts types automatically when possible.
Explain what the
declare(strict_types=1); directive does in PHP and why you might want to use it.Think about how PHP normally handles types and what changes with strict types.
You got /4 concepts.
Describe where and how to correctly place the
declare(strict_types=1); directive in a PHP file.Consider the file structure and PHP parsing rules.
You got /3 concepts.