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?
CodePudding user response:
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.
CodePudding user response:
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