Time to Use PHP Return Types in Your Code

php elephant

Introduction: What is a Return Type in PHP and Why Does it Matter?

PHP is a loosely typed language that allows programmers to mix data type returned by a function. If something goes wrong, a typical practice is to return false from a function, or data is returned if everything went OK. This is called mixed return type.

A mixed return type function is depicted in the code below.

1
2
3
4
5
6
7
8
9
10
11
12
// return mixed type
public function getTableData($table){
    $records = [];
    $records = $this->db->getRecords($table);


    if (!empty($records)) {
        eturn $records;
    }else{
        return false;
    }
}

Above function returns database records or false. The issue is that returning false doesn’t catch specific error, so we won’t know how the function failed and what to fix. For instance, when returning false, it could be due to misconfigured database connection; it could be caused by an empty database table; or it could even be wrong table name passed.

Without a return data type to enforce some restrictions on the value returned, and in case of anomaly, the caller function cannot know how to catch and address exception since it will not know exactly what type will return.

What are the different types of Return Values in PHP?

Luckly, in PHP 7, a new feature, return type declarations has been introduced to specify the kind of result that a function return. To support return type in PHP functions, you need to include a simple declaration at the top of the PHP file.

1
declare(strict_types=1);

After that, you can specify the return type in the following fashion:

1
2
3
4
function foo(): int {
    // ...
    return bar;
}

If the function tried to return boolean, you will see a TypeError is raised.

1
PHP Fatal error: Uncaught TypeError: Return value of foo() must be of the type integer, boolean returned.
    The following return types are supported

  • int
  • float
  • bool
  • string
  • array
  • callable
  • interfaces
  • object (PHP 7.2+)

You can also declare a nullable return type by putting a question mark in front of the return data type.

1
2
3
4
function foo(): ?int {
    // ...
    return bar;
}

In this case, return type of function foo() can be either an integer or null.

With return type support, we can then create functions with less ambiguity.

Incorporating return types in PHP

Unlike Java or C++, PHP is still not a strongly typed language, one should start making a good practice to be precise of what a function/method will return in your code. We shouldn’t try to guess what variable has what type. Being clear about data types has a lot of advantages both for code readability, maintainability, and speed.

So if you are already using PHP 7 or 8, include the strict mode declaration, and start making a habit to add return types in your functions today!

Additional reads

https://www.php.net/manual/en/language.types.declarations.php