0
0
PHPprogramming~15 mins

Declare strict_types directive in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Declare strict_types directive
📖 Scenario: You are writing a PHP script that performs simple math operations. To ensure your code treats numbers strictly as integers and avoids unexpected type juggling, you want to enable strict typing.
🎯 Goal: Learn how to declare the strict_types directive in PHP and see how it affects function behavior.
📋 What You'll Learn
Create a PHP file starting with the strict_types declaration
Define a function that accepts an integer parameter
Call the function with an integer and a string representing a number
Observe the difference strict typing makes
💡 Why This Matters
🌍 Real World
Strict typing helps developers write more reliable PHP code by catching type errors early, which is important in large projects and APIs.
💼 Career
Many PHP jobs require understanding strict typing to maintain code quality and avoid bugs caused by unexpected type conversions.
Progress0 / 4 steps
1
Add the strict_types directive
At the very top of your PHP file, write declare(strict_types=1); to enable strict typing.
PHP
Need a hint?

The declare(strict_types=1); directive must be the first statement after the opening <?php tag.

2
Define a function with an integer parameter
Define a function called double that takes one parameter int $number and returns $number * 2.
PHP
Need a hint?

Use int $number to enforce the parameter type and : int to specify the return type.

3
Call the function with an integer and a string
Call the double function twice: once with the integer 5 and once with the string '5'. Assign the results to variables $result1 and $result2 respectively.
PHP
Need a hint?

Call the function exactly as double(5) and double('5') and assign to the specified variables.

4
Print the results
Print $result1 and $result2 each on a new line using echo. This will show how strict typing affects the second call.
PHP
Need a hint?

Because strict typing is enabled, calling double('5') will cause a TypeError and the script will stop before printing the second result.