I am used to using the following generic syntax to define a custom function in a PHP class:
public function my_function(arg1, arg2, ...)
{
//Cuerpo de la función, con o sin retorno
}
I recently saw a piece of code that had a function defined with the following syntax:
public function my_function(arg1, arg2, ...): array
{
//Cuerpo de la función, con o sin retorno
}
I've searched the PHP documentation and googled, and haven't found a clear explanation of what the part : array
in the function declaration does, or why it's there, or anything concrete.
Does anyone know what this is about, or how it works?
This is known as Return Type Declaration , it is a new type of syntax introduced in PHP 7, to declare the data type that the method returns (in this case an array ).
This is not just limited to arrays , you can use
int
,float
even your own classes:These are not just for ease of reading. If the function returns a different type than the one indicated, the value will be converted to the indicated type. If it cannot be forced, or strict mode is enabled, an
Type Error
.Information obtained from:
Colon after method declaration?
For more information you can review the documentation:
Return Type Declarations
Since PHP 7 you can define in a function declaration the type of return you expect. In your case, for example, it expects an array to be returned, and if not, it may throw a TypeError exception.
Source: https://www.php.net/manual/es/functions.returning-values.php#functions.returning-values.type-declaration
Complementing what has already been mentioned, remember that you must also declare a data type for the arguments , so that in this way the interpreter recognizes not only what value the function is going to return, but also knows what type of values it expects as arguments of the function. function; thus:
This would work because I tell it to expect a string as an argument, and I pass a string when I call the function:
Departure:
However, if I still declare the output element of the function to be an array, but I pass a value other than the expected value (a string) as an argument, I will get a functional output like this:
Will print:
For the previous case, if it is returning a vector, but not with the expected values, for this case we must at the beginning, after the opening tag, declare the following directive:
So if we try to repeat the execution it will give us
While if the intentions are:
So it could be like this:
Each element is identified by referring to the expected data type, although these are different , passing these arguments to the function we will obtain:
As long as one of the two arguments does not respect the expected data type, even if you indicate that the return is a vector, you will again have a Fatal error referring to what has already been mentioned.
Documentation