Please wait

Type Hints

Type hinting in PHP is a feature that allows you to specify the expected data type of arguments in function declarations. By using type hinting, you can specify that a function must receive variables of a certain type. If the data passed to the function is not of the specified type, PHP will throw an error and stop execution.

Type hinting is completely optional. Using type hints can help prevent bugs and misunderstandings in your code by making sure that functions are used with the correct type of data. It also makes your code easier to understand and work with, especially in larger codebases.

Type Hinting Parameters

Here's an example of type hinting with an array:

function printArray(array $input) {
  foreach ($input as $value) {
    echo $value . "<br>";
  }
}
 
 
printArray(array('one', 'two', 'three'));  // This works fine
 
printArray('hello world');  // This will throw an error

In this example, the function printArray() expects an array as its argument. If you try to pass something that's not an array, PHP will throw a TypeError.

We can use any of the data types:

  • string
  • float
  • int
  • array
  • bool
  • mixed

Type hinting return values

You can also specify the return type of a function like so:

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

In this case, the add() function expects two integers as arguments and will also return an integer. If the return statement in the function tries to return a value that's not of the declared type, PHP will throw an error.

Mixed data type

The mixed data type is a pseudo-type available in PHP, which indicates that a variable or a return value may contain multiple (or any) types of data.

The mixed type can be one of the following:

  • array
  • boolean
  • callable
  • integer
  • float
  • string

For example, if a function can return a string, an integer, or null, you might use the mixed type to indicate this. Here's an example:

function exampleFunction($input): mixed {
  // Some logic that might return integer, string or null
}

Note: The mixed type was officially introduced in PHP 8.0. Before PHP 8.0, the term "mixed" was used informally in documentation and code comments to indicate that a variable could be of any type, but there was no formal mixed type that you could use in your code. As of PHP 8.0, you can use mixed as a formal type in your function signatures and property declarations.

Remember, if possible, it's generally better to be specific about the types your functions expect and return. Using mixed can make your code harder to understand and more prone to errors because it provides less information about what the function expects or returns.

Union types

The mixed type is great, but you may only want to support two or three types. You're not forced to use one type or support all types. Union types are a feature introduced in PHP 8.0 that allows you to declare a variable, parameter, or return type as one of several potential types.

Before PHP 8.0, you could only type hint a single type for a function parameter or return type. But with union types, you can specify that a parameter or return type can be of more than one type. You can declare multiple types by separating them with the | character.

Here's an example of a function with a union-type hint:

function getArea(int|float $length, int|float $width): int|float {
  return $length * $width;
}

In this example, the getArea() function can accept either integers or floats as its parameters, and it can return either an integer or a float.

Union types provide greater flexibility in your code by allowing functions to accept and/or return different types of data.

Enabling strict types

By default, PHP doesn't automatically throw errors when the incorrect types are used as parameter values or return types. Instead, PHP performs type coercion/type juggling.

This is sometimes called "weak typing". For example, if you have a function that expects an integer and you pass a string that looks like an integer (like '123'), PHP will automatically convert the string to an integer, and the function will still work. While this can be convenient, it can also lead to unexpected behavior and hard-to-find bugs.

Here's an example to illustrate the behavior:

function add(int $a, int $b) {
  return $a + $b;
}
 
echo add('3', '4');

With weak typing (the default), the add() function works fine even though we're passing strings. PHP automatically converts the strings to integers.

In PHP, you can enable strict types by adding the declare(strict_types=1); directive at the top of your file. This must be added at the top of the file after the opening <?php tag.

<?php
declare(strict_types=1);
 
// Rest of your PHP code...

When strict types are enabled, PHP will throw an error if the type of a value doesn't match the type hint exactly. This means that PHP won't do any automatic type conversion (coercion) to match the type hint. Without strict typing (the default behavior), PHP will automatically convert types where possible.

Let's look at the example as before but with strict typing enabled:

declare(strict_types=1);
 
function add(int $a, int $b) {
  return $a + $b;
}
 
echo add('3', '4');

With strict typing, this code will throw an error because the add() function expects integers, and we're passing strings. PHP won't do any automatic type conversion.

Why strict typing?

There are many benefits to using strict typing:

  • Error Prevention: With strict typing, PHP will not automatically convert mismatched types, which could prevent unintended results or errors caused by unexpected type conversions. This can be especially helpful in complex projects where variables are passed through multiple layers of functions.
  • Code Quality: Using strict types makes the code more predictable and easier to reason about, which is especially beneficial in large projects or when working with a team. It enforces a certain level of code quality by making sure that functions are used as intended, and variables are of the expected type.
  • Improved Debugging: Strict typing can make bugs related to type mismatches easier to find and fix. Instead of silently converting types and potentially causing subtle bugs, PHP will throw an error when a type mismatch is encountered, making it easier to spot and correct the issue.
  • Documentation: When strict typing is used, the type of each argument is explicitly stated in the function declaration, which can serve as a form of documentation. Developers reading the code can easily understand what types of values a function expects without having to rely on comments or additional documentation.
  • Performance: While the performance benefits might be negligible in most applications, type checking can sometimes result in faster code execution as PHP doesn't need to infer and juggle types.

Remember, the use of strict typing can also depend on the specific needs and coding standards of your project. While it can provide several benefits, it also requires careful attention to correctly match data types throughout your code.

Key takeaways

  • Type hinting in PHP allows you to specify the expected data type for function arguments and return values.
  • The mixed data type is a pseudo-type in PHP that indicates a variable can contain any type of data: int, float, string, array, bool, etc.
  • Union types, introduced in PHP 8.0, allow you to declare that a variable, parameter, or return type can be one of several types. They can be declared by separating types with the | character.
  • You can enable strict typing in PHP with the declare(strict_types=1); directive at the top of your file.
  • With strict typing, PHP won't automatically convert mismatched types, preventing potential bugs due to unexpected type conversions.

Comments

Please read this before commenting