Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing function's return type declaration - do declarations increate efficiency

Is there any benefit in including a return type declaration in a php class function? Is this better:

public function team_classes(): \Illuminate\Database\Eloquent\Relations\HasMany
{
    return $this->hasMany(TeamClass::class, 'activity_id', 'id');
}

is the above better than the following?

public function team_classes()
{
    return $this->hasMany(TeamClass::class, 'activity_id', 'id');
}

and if so, is it only for the programmers eye's or does it increase efficiency / speed?

like image 769
Robert Bryan Davis Avatar asked Jun 20 '26 07:06

Robert Bryan Davis


2 Answers

Adding return type declaration is recommended, but not mandatory. It provides you with advanced IDE autocompletion and type compatibility support.

For instance, if you don't have type declaration on your relationship, your IDE will most likely not provide you with relationship methods.

Another reason why you might want to opt in using types is runtime type checking. Try adding an incorrect return type to your example above (instead of returning HasMany type use anything else). This will throw an exception whenever you use that method.

As for speed: it almost does not impact your application. You can find type-hinting comparisons online, but from what I see the difference is about 2-5ms.

Overall, this provides better IDE support and implicit type declarations, which make developer life easier.

like image 139
Andrii H. Avatar answered Jun 23 '26 00:06

Andrii H.


Actually, older versions of PHP did not have this feature so they called PHP as duck taped but after the latest version you have return types and typed variables etc. If return type is important or argument types of your function it is a good practice to put return types.

In your code, you better put these return types or variable types because you do not want to assign some string to an integer or something like that, or sending collection while the function expecting you to send array. It will protect you as a developer from doing mistakes or doing less mistakes and it honestly it will make your life easier when debuging your code.

You can also use like this:

use lluminate\Database\Eloquent\Relations\HasMany;

public function team_classes(): HasMany
{
    return $this->hasMany(TeamClass::class, 'activity_id', 'id');
}

It is good practice to use FQDN

like image 26
gguney Avatar answered Jun 22 '26 23:06

gguney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!