PHP has evolved from a purely weakly-typed language to one that supports strict typing. Understanding type declarations is crucial for modern PHP development.

Basic Type Declarations

PHP supports several type declarations for parameters and return values:

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

Available Type Declarations

  • Scalar types: int, float, string, bool
  • Compound types: array, iterable, object
  • Special types: callable, self, parent
  • Nullable types: ?string, ?array (PHP 7.1+)

Strict vs Weak Typing

PHP uses weak type checking by default, but you can enable strict mode:

declare(strict_types=1);

function divide(float $a, float $b): float {
    return $a / $b;
}

// This will throw TypeError in strict mode
divide("10", 2.5);

Union Types (PHP 8.0+)

Specify multiple possible types:

function displayValue(int|string|float $value): void {
    echo $value;
}

Return Type Variance

PHP 7.4 introduced covariant return types:

interface Factory {
    public function make(): object;
}

class UserFactory implements Factory {
    public function make(): User {
        return new User();
    }
}

Proper use of type declarations makes your code more predictable, self-documenting, and less prone to runtime errors.

By Admin

Leave a Reply

Your email address will not be published. Required fields are marked *