Back to Blog
Lesson 4 of the PHP: Modern PHP from the Ground Up course
July 15, 20264 min read

Strong Typing and Scalar Type Hinting in Modern PHP

Stop debugging runtime type errors. Learn to use scalar type hints and strict typing in PHP to write predictable, professional code from the start.

Close view of computer screen displaying HTML code with an authentication error.

Previously in this course, we covered PHP Variables and Data Types: A Beginner's Guide, where we explored how PHP handles dynamic data. In this lesson, we are taking a significant step toward professional development by introducing type hinting and strict typing.

PHP is historically a "loosely typed" language. This means it often tries to guess what you mean when you pass the wrong type of data to a function. While convenient for quick scripts, this "helpful" behavior is a major source of bugs in larger applications. By using scalar type hints, we force PHP to be explicit about the data it expects.

Understanding Scalar Type Hints

A "scalar" type refers to the basic data types: int, float, string, and bool. In older versions of PHP, you could only hint objects or arrays in function signatures. Modern PHP allows you to demand these specific scalar types for function arguments and return values.

When you add a type hint, you are creating a contract. You are telling the rest of your application: "This function will only work if you give me exactly what I've asked for."

A Worked Example

Imagine we are building a simple calculator for our project. Without type hints, a function might behave unexpectedly if someone passes a string instead of a number.

PHP
#6A9955">// Without type hints
function addNumbers($a, $b) {
    return $a + $b;
}

echo addNumbers(5, "10 apples"); #6A9955">// PHP might try to force "10 apples" into 10, resulting in 15.

This is dangerous. Let's make it robust using PHP syntax for type hinting:

PHP
declare(strict_types=1);

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

#6A9955">// This works perfectly
echo addNumbers(5, 10); 

#6A9955">// This will throw a TypeError, preventing a silent logic bug
echo addNumbers(5, "10"); 

The Power of Strict Typing

Detailed view of metallic typebars on an old typewriter highlighting its mechanical complexity.

The declare(strict_types=1); line at the top of your file is the most important part of this lesson. By default, PHP will still try to coerce (convert) types if they are "close enough" (like a string containing a number).

When you enable strict mode, you disable this coercion. If you pass a string to a function expecting an integer, PHP will immediately throw a TypeError. This is exactly what you want—it's better for your script to crash during development than to produce incorrect data in your production database.

Comparison: Default vs. Strict Mode

FeatureWeak Typing (Default)Strict Typing (strict_types=1)
add(5, "10")Returns 15 (coerces string)Throws TypeError
PredictabilityLow (Implicit behavior)High (Explicit behavior)
DebuggingHard (Logic errors)Easy (Immediate crashes)

Hands-on Exercise

It is time to apply this to our running project. Open your project's main logic file. Create a function called calculateTax that accepts a float as a price and returns a float representing the total price with a 10% tax added.

  1. Add declare(strict_types=1); to the top of your file.
  2. Define the function: function calculateTax(float $price): float.
  3. Inside, return $price * 1.10.
  4. Try calling the function with an integer (e.g., 50) and a string (e.g., "fifty"). Observe how the TypeError protects your application.

Common Pitfalls

  • Forgetting the Declaration: The strict_types=1 directive only applies to the file in which it is declared. It does not affect other files in your project. You must add it to every file where you want strict enforcement.
  • Case Sensitivity: Always use lowercase for scalar types (int, string, bool, float). Using Int or String will be treated as class names, not scalar types.
  • The Nullable Trap: If you need a value to be an int or null, you must explicitly allow it using a question mark: function compute(?int $value).

FAQ

Q: Should I use strict typing everywhere? A: Yes. In modern PHP development, there is almost no reason not to use strict_types=1. It makes your code self-documenting and significantly easier to maintain.

Q: Does this affect performance? A: The impact is negligible. The safety benefits far outweigh the microscopic overhead of type checking.

Q: What if I don't know the type in advance? A: If a parameter can be multiple types, you can use union types (e.g., int|float $value), which we will cover in later architectural lessons.

Recap

Wooden Scrabble tiles spelling 'RECAP' on a brown textured background. Text concept image.

By using scalar type hints and strict_types=1, we move away from the "guesswork" of older PHP and toward a robust, professional standard. You have now learned how to define explicit contracts for your functions, ensuring that data flows through your application exactly as you intend.

Up next: Conditional Logic with If-Else — where we'll use these typed variables to make real decisions in our code.

Similar Posts