0
0
PHPprogramming~20 mins

Why strict typing matters in PHP - See It in Action

Choose your learning style9 modes available
Why strict typing matters
📖 Scenario: Imagine you are building a simple calculator that adds two numbers. Sometimes, the numbers might come as strings, and sometimes as integers. Without strict typing, mistakes can happen silently, causing wrong results.
🎯 Goal: You will create a PHP script that shows how strict typing helps catch errors early by enforcing the types of inputs to a function.
📋 What You'll Learn
Create a function with strict typing enabled
Define a function that adds two integers
Try calling the function with a string and an integer
Observe the error caused by strict typing
💡 Why This Matters
🌍 Real World
Strict typing is important in real-world PHP projects to avoid bugs caused by unexpected data types, especially when working with user input or external data.
💼 Career
Many PHP jobs require writing reliable and maintainable code. Understanding strict typing helps you write safer functions and avoid common errors.
Progress0 / 4 steps
1
Enable strict typing and create the add function
Write the first line declare(strict_types=1); to enable strict typing. Then create a function called add that takes two integer parameters int $a and int $b and returns their sum as an integer.
PHP
Need a hint?

Start your PHP file with declare(strict_types=1); to turn on strict typing. Then define the function with int type hints for parameters and return type.

2
Call the add function with integer arguments
Call the add function with two integers: 5 and 10. Store the result in a variable called $result.
PHP
Need a hint?

Call the function with two numbers and save the answer in $result.

3
Call the add function with a string and an integer
Call the add function with a string '5' and an integer 10. Store the result in a variable called $result2.
PHP
Need a hint?

Try passing a string instead of an integer to see how strict typing stops this.

4
Print the results
Print the variables $result and $result2 using echo statements, each on a new line.
PHP
Need a hint?

Print both results. The first will show 15. The second will cause a TypeError because of strict typing.