Return type declarations in PHP

Timothy Iloba
6 min readFeb 12, 2024

--

Hey everyone, welcome to another blogpost. In this blogpost, we will be discussing a very important concept in PHP. This concept helps us write predictable and less error prone code.

Let’s dive in.

What is return type declaration all about? It’s a very easy to understand concept.

In PHP, return type declarations simply help us to clearly specify the expected data type of the value that our functions or class methods will return. I believe you will understand it better after this simple example.

Let’s say we have an application that stores users. So, in this app, we collect our users’ data like their name, age, gender and year of birth and store them in our database. (In this case, we will be storing them in an array for simplicity)

Take a look at the code example below

<?php

class User
{
public function __construct(
public string $name,
public int $age,
public string $gender,
public int $yearOfBirth
) {
}
}

From the code above, we can see that we have a User class and we are using constructed promoted properties to set up our user class to create user objects. From what we have, we can see that our user class has the name, age, gender and yearOfBirth attributes. Next up, let’s take a look at our Database class

<?php

class Database
{
public array $users;

public function __construct(public string $name)
{
}

public function addUser(User $user): void
{
$this->users[] = $user;
}

public function getNumberOfUsers(): int
{
return count($this->users);
}
}

From the code above, we can see that we have a public property called users which is an array and is going to store all our users and we can also see that we have two methods, the addUser which adds a user to the users array and the getNumberOfUsers method which returns the total count of the users that have been added to the users array.

Now, pay attention, I am sure you noticed two keywords after we declared our methods. I am talking about the “void” after the public function addUser(User $user) and the “int” after the public function getNumberOfUsers().

public function addUser(User $user): void 
{
$this->users[] = $user;
}



public function getNumberOfUsers(): int
{
return count($this->users);
}

Those two keywords are the return type declarations we specified. For the first method addUser, we added the void keyword. What that simply means is that the method “addUser” will not return any value, which is actually correct. If you take a closer look, you will notice that the method has just one task, which is to add a user to the users array, and that’s all it does. It does not return any value at all and that is why we specified our return type as “void”. In the world of programming, whenever void is used as a return type declaration, it simply means that the said function or method does not return any value.

I hope you got that. Now let’s examine the second method: getNumberOfUsers. From this method, we can see that the keyword int was used after the method declaration. That simply means that the said method will return an integer value. You can now understand right? That’s it. If you examine the method carefully, you will notice that it simply returns that total count of our users and truly, that value returned will surely be an integer. It’s very easy to understand.

If we go back to our explanation of return type declarations above, we said that it simply helps us specify the datatype of the value our methods or function will return and that’s it. You can see that from our example above, we specified that our addUser method will return no value by adding the void keyword and also that our getNumberOfUsers will return an integer value by adding the int keyword.

Return type declarations have several benefits but we will discuss a few.

The first benefit of return type declaration is that it gives our code Clarity. When you use return type declarations, it is easier for you to understand your code and not just that, it makes it easier for other developers to understand your code. From looking at our example above, anyone who looks at our Database class will easily tell that the addUser method does not return any value and that the getNumberOfUsers method returns an integer value.

Another benefit of using return type declarations is that our client code will have confidence in the value it will be receiving without having to perform its own manual checks.

Take a look at this example below: let’s say we need to get the number of new users in our app. So, we will have to first of all get the number of all users and then deduct the last count of users from it. In this case. We will assume that we had just one previous user:

$lastUsersCount = 1;

$database = new Database(“users”);

$newUsers = $database->getNumberOfUsers() - $lastUsersCount;

So, you can see from the above code that we initialized a variable called lastUsersCount to store the total number of previous users we had and then we then deducted it from the total number of users which we got by calling our getNumberOfUsers() method. We then assigned the value to the newUsers variable.

Before we move on, let’s examine this code. You can see that from the code above, we are directly deducting our lastUsersCount from whatever is returned from the getNumberOfUsers method. You might want to ask, how are we even sure that getNumberOfUsers() will return an integer? That’s a good question. Let’s take for instance that it returned an array and now you can see that we are trying to deduct our lastUsersCount from it and that would have made our code break. But in this case we are very confident that our getNumberOfUsers() method will return an integer because we used return type declaration and clearly specified that It will return an integer. This has saved us the stress of dealing with unwanted errors and also having to do manual checks.

Before now, we would have had to do manual checks like so to make sure that the getNumberOfUsers method returned an integer value:

if (is_int($database->getNumberOfUsers()) {
$newUsers = $database->getNumberOfUsers() - $lastUsersCount;
}

And you can see how messy the code looks.

So, one of the main benefits of return type declaration is that it gives us this confidence that wherever we call our methods from, we can be 100% sure that it is returning the right value.

Another benefit of using return type declarations is that it helps us prevent unexpected errors. When you always declare return types, PHP will always help you catch errors early. This is because it will always check to make sure that the value your method is returning always matches the return type you specified. Let’s paint this scenario with our code example above. Let’s say we change the implementation of our addUser method and make it return the users array. As we know, previously it’s job was just to add a user to the users array. When we make this change, PHP will throw an error because we already declared that the method was supposed to return no value at all (void). Take a look at our modified method below.

public function addUser(User $user): void 
{
$this->users[] = $user;
return $this->users;
}

So, we are now returning a value which is the user array itself but our return type declaration is still void and that will cause PHP to throw an error. See error below…

PHP Fatal error:  A void function must not return a value in /Users/……

How do we fix this error??

All we need to do is change the return type declaration to match whatever the method is returning and, in this case, our method is returning the users array and thus we should change our return type declaration from void to array like so:

public function addUser(User $user): array 
{
$this->users[] = $user;
return $this->users;
}

That’s basically it. Your return type declaration should always match whatever value your method is returning. So, for instance, if your method is returning a string datatype, your return type declaration should be string, if it is returning a Boolean, your return type declaration should be bool etc.

Remember, always make sure your returned value and your return type declarations match.

I hope you now understand return type declarations? Thanks for reading.

If you are interested in seeing return type declarations explained in a video format, feel free to check out this full PHP Object oriented course from the guy who taught me!

https://garyclarketech.teachable.com/p/learn-object-oriented-php. Everything you need to understand Object Oriented programming is covered there.

You can grab yours now and get a 20% discount. All you have to do is use this promo code: GCTREPO20 when making your purchase.

You can access all the codes used in this post here: https://github.com/GaryClarke/blog-code-examples/tree/5-return-type-declaration

--

--

Timothy Iloba

Let's work our way up into being world class PHP developers. We will focus on understanding the basics and important concepts as that is what will set us apart.