Defining function return & argument types in PHP

In order to make sure our code consistently returns the type of data that we expect it to return, we can make sure the data is casted to the specified data types by specifying it as a return type.

Lets define this return type, which is the expected return value of a function. If we look at getPosts, we can easily see that we are returning an array. To make sure this function always returns an array, no matter what, we will specify array as a return type. We can do this after the close parenthesis by specifying a colon, and then the data type of the return value that we want to enforce it to. So this will be a colon, followed by the array keyword:

function getPosts(): array
    return [

If we look at the getPostText function, we can see that our final result is returning a string. Similarly, let’s define that as a return type with a colon, a space, and then the string keyword.

function getPostText($numPosts): string
    return $numPosts === 1 ? 'post' : 'posts';

You’ll want to specify a function return type in every function you write to make sure that the function is returning the data you expect it to return. This helps enforce the integrity of your codebase so that when you call a function, you can always expect it to return the same type. For example, you would never want getPostText to return an array or some other value, as that would break any code that is calling and displaying the output of this function call.

Just like return types, we can also cast arguments to specific types. This should also be done throughout your entire codebase. By defining an argument as a specific type, PHP will ensure this value is casted to this type, which will make your code more reliable.

We can do this by specifying the type we want arguments to cast to before the name of the argument variable. For example, we want $numPosts to always to an integer, so let’s define the argument of $numPosts to the type of int.

function getPostText(int $numPosts): string
    return $numPosts === 1 ? 'post' : 'posts';

Complete and Continue  
Extra lesson content locked
Enroll to access source code, comments & track progress.
Enroll for Free to Unlock