Type Hinting

Last updated on

PHP type hinting is a feature that allows developers to specify the data type of a parameter or the return type of a function in their PHP code. It was introduced in PHP 5, bringing a level of type safety to the language.

Type hinting helps developers catch potential bugs early in the development process and makes the code more readable and self-documenting.

There are several aspects of type hinting in PHP:

Parameter Type Hinting

When defining a function or a method, you can specify the expected data type for one or more parameters. This ensures that the function or method is called with the correct types of arguments. If a mismatch occurs, PHP will throw a TypeError at runtime.

<?php
function calculateSum(int $a, int $b) {
    return $a + $b;
}
?>

In this example, calculateSum expects two integer parameters and returns the sum of both parameters.

In the following section, you will see another example of how to use type hinting in a function to specify the return value type.

Return Type Hinting

You can also specify the expected return type of a function. This helps both developers and IDEs understand what type of value is expected from a function call.

For example:

<?php
function multiply(int $a, int $b): int {
    return $a * $b;
}
?>

Here, multiply is expected to return an integer; otherwise, it will show an error like the following example:

<?php

function multiply($x, $y): int{
    return "Hello World!";
}

echo multiply(2, 10);
?>

Here is the error:

fetal error uncaught error

Anyway, let’s see another example of how to handle the parameter if it is a callable from another function and how to return its value.

Using Type Hints with Callable Functions

In PHP, using type hints with callable functions allows you to specify the type of a function parameter as callable. This means that the argument passed to the function must be a valid PHP callable, which can be a function name, an anonymous function, or an array containing an object and a method name.

Here’s an example:

<?php

function toExecute() {
  return "Hello CodedTag Students";
}

function myFunction(callable $myParam): void {
  echo $myParam();
}

myFunction("toExecute"); // Output: Hello CodedTag Students
?>

In this PHP code snippet, there are two functions defined: toExecute and myFunction. The toExecute function simply returns the string “Hello CodedTag Students.” The myFunction function takes a callable parameter $myParam and prints the result of calling that callable. The : void in the function declaration specifies that the function does not return a value.

The last part of the code calls myFunction with the argument “toExecute.” In PHP, you can pass the name of a function as a string to a callable parameter. Inside myFunction, the provided callable (in this case, the function name “toExecute”) is invoked using $myParam(). As a result, “Hello CodedTag Students” is printed, and that’s the output of the code.

Let’s explore another type of type hinting in PHP, which is a feature introduced in PHP 7.1.

Nullable Types (PHP 7.1 and later)

With PHP 7.1 and later, you can also specify that a parameter or return type can be null. This is achieved by appending a ? to the type declaration.

<?php
function process(?string $name): ?string {
    if ($name === null) {
        return null;
    }
    return "Hello, " . $name;
}
?>

In this example, process accepts a nullable string and returns a nullable string.

Let’s proceed to the section below to explore how to use type hinting in PHP with classes and interfaces.

Using PHP Type Hinting with Classes and Interfaces

Type hinting can be employed in class methods, whether in the form of passing a class as a parameter or within constructors. This practice ensures that objects are created and used with the correct types.

For example:

<?php 

class MyClass {
    // ...
}

// Type hint here: the parameter should be of the class name
function explorer(MyClass $obj) {
    // ...
}

$obj = new MyClass();
explorer($obj); // works

$str = "hello";
explorer($str); // throws TypeError

?>

In the example above, the explorer() function takes a parameter of type MyClass. The function expects an instance of the MyClass class as an argument and will throw a TypeError if any other data type is passed.

Let’s take an example to illustrate the same concept within an interface as well.

<?php 

interface MyInterface {
    // ...
}

class MyClass implements MyInterface {
    // ...
}

function explorer(MyInterface $obj) {
    // ...
}

$obj = new MyClass();
explorer($obj); // works

$str = "hello";
explorer($str); // throws TypeError
?>

Anyway, in PHP, you can specify the parameter as a mixed type. Let’s see how it works.

The Mixed Type in PHP Type Hints

The mixed type is a type hint introduced in PHP 8.0. It represents a type that can be any type at all, and it is used to indicate that a function or method parameter, or the return type, can accept or return values of any data type.

Here is an example of how mixed type hinting can be used:

<?php
function processMixed(mixed $data): mixed {
    // Function code goes here
    return $data;
}
?>

In this example:

  • The function processMixed takes a parameter named $data with a type hint of mixed. This means that $data can be of any type—integer, string, array, object, etc.
  • The return type of the function is also specified as mixed, indicating that the function can return a value of any type.

The mixed type is particularly useful in scenarios where the exact type of data is not known beforehand or when a function needs to be very flexible in terms of the types it can handle.

One other thing you can do with type hints is use union types. Let’s take a look at this concept in the section below.

Type Hinting with Union Types in PHP

Type hinting with union types is a feature introduced in PHP 8.0 that allows developers to specify multiple types for a function parameter or return type. This provides more flexibility compared to a single type hint, allowing for a broader range of accepted types. Union types are specified using the pipe (|) symbol between the type names. Let’s see examples.

Using Union Types in Function Parameters:

<?php
function processInput(int|string $data): void {
    // Function code goes here
}
?>

In this example, the processInput function takes a parameter named $data with a union type hint of int|string. This means that $data can be either an integer or a string.

Using Union Types in Return Types:

<?php
function fetchData(): array|string {
    // Function code goes here
}
?>

Here, the fetchData function specifies a return type of array|string. It can return either an array or a string.

Let’s explore how to handle ‘self’ and ‘parent’ in type hinting.

Self and Parent in PHP Type Hinting

In PHP, you can use self and parent as type hints to refer to the current class and its parent class, respectively. This feature is particularly useful when you want to enforce that a method returns an instance of the same class or a subclass.

For example:

<?php

class MyClass {
    public $number = 10;
    public function myFunction(self $myParam): self{
        // Function code goes here
        return $myParam;
    }
}

$obj = new MyClass();
echo $obj->myFunction($obj)->number; // 10

?>

In this example, we specify that the parameter $myParam and the function should both be instances of the MyClass class.

Let’s summarize it.

Wrapping Up

PHP type hinting is a powerful feature introduced in PHP 5, contributing to enhanced code quality and readability. It enables developers to specify the expected data types for function parameters and return values. This proactive approach aids in identifying potential errors early in the development process, making the codebase more robust.

The various aspects of PHP type hinting, such as parameter type hinting and return type hinting, provide clear guidelines for developers and IDEs, facilitating better understanding and maintenance of code. Additionally, the introduction of nullable types in PHP 7.1 allows for more flexibility in handling null values.

The utilization of type hinting extends beyond basic data types to more advanced scenarios, including callable functions and the introduction of mixed types in PHP 8.0. The latter allows functions to handle parameters and return values of any data type, offering unparalleled flexibility.

Furthermore, type hinting seamlessly integrates with classes and interfaces, ensuring that objects are used correctly and preventing runtime errors. The introduction of self and parent in PHP type hinting further refines this capability, allowing developers to enforce specific class relationships.

Finally, PHP 8.0 introduces union types, enabling the specification of multiple accepted types for function parameters and return values. This feature enhances the expressiveness of type hinting, allowing for a broader range of accepted data types.

Share on: