php-tipos-de-datos-y-tipado-estricto-en-php

Data Types and Strict Typing in PHP

  • 4 min

A data type is the category that determines what values a piece of data can contain and what operations it supports.

In the old days, PHP was the “Wild West” of types. You could add an apple and a pear and the language would try to give you a result instead of an error.

PHP retains dynamic typing, but it allows declaring types in parameters, return types, and properties. This lets us clearly express what data we expect to receive and what we are going to return.

This is not academic pedantry; it’s the difference between an application that fails silently and one that warns you before you make the mistake.

Scalar Types

Scalar types are the basic building blocks of information. In PHP, we have four main ones:

  • int: Whole numbers (e.g., 42, -10).
  • float: Decimal or floating-point numbers (e.g., 3.14, 1.5).
  • string: Text strings (e.g., "Hello world").
  • bool: Truth value (true or false).

These are joined by other special types like null (absence of value), array (lists), object (classes), and void (when a function returns nothing).

Type Hinting

Type Hinting is the way to tell PHP: “This function needs an integer, don’t give me anything else”.

We can type both arguments (input) and the return (output).

// Without Type Hinting (The old style)
function sum($a, $b) {
    return $a + $b;
}
// What happens if I call sum("hello", [1,2])? Chaos!

// With Type Hinting (The modern style)
function sum(int $a, int $b): int {
    return $a + $b;
}
Copied!

Notice the syntax:

  1. We put the type before the variable: int $a.
  2. We put the return type after the colon: : int.

Now the code documents itself. If you read the function, you know exactly what it needs to work.

The Problem of “Coercion” (Weak Typing)

By default, PHP is still “friendly.” If you have a function that expects an int and you pass the text "5", PHP will say: “Well, it looks like a number, I’ll convert it to 5 and carry on”.

This is called Type Coercion.

While sometimes useful, it can hide errors. A numeric string like "5" can be converted to an integer in coercive mode, while a non-numeric text like "5 apples" will cause a TypeError when passed to an int parameter.

Activate declare(strict_types=1);

To activate PHP’s strict mode, we need to add a special instruction on the first line of the file, before anything else.

<?php
declare(strict_types=1);

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

// Scenario 1: Correct
echo sum(2, 3); // Output: 5

// Scenario 2: Fatal Error
echo sum(2, "3"); 
// Error: Argument #2 must be of type int, string given
Copied!

When you activate strict_types=1, PHP stops automatically converting scalar types on calls made from that file. If the function expects an integer and you give it a string, it will throw a TypeError. This directive does not change dynamic variable typing and does not apply in the same way to all internal PHP functions.

Why Use It Always?

It’s better for the program to fail on your computer while you are developing (and for you to fix it on the spot) than for it to fail in production with corrupt data because PHP tried to “guess” the data type incorrectly.

Union Types

Sometimes life isn’t black or white. Sometimes a variable can be one thing or another. Since PHP 8, we can express this with the vertical bar |.

Imagine you are looking up a product by ID. That ID could be a number (150) or a code ("PROD-150").

function findProduct(int|string $id): void {
    // Logic to search...
    echo "Searching product: " . $id;
}
Copied!

This is very powerful because we maintain control (we know it will be an int or string) without losing flexibility.

The mixed Type

There is a type called mixed which means “accepts anything.”

  • Advice: Only use it when you have no other choice. If you use mixed for everything, you are going back to old PHP and losing the advantages of typing.