0
Reading in:
https://secure.php.net/manual/en/mi
found out the following example:
function arraysSum(array ...$arrays): array
{
return array_map(function(array $array): int {
return array_sum($array);
}, $arrays);
}
print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));
But understand that arraysSum
in its definition has only 1 argument;
arraysSum(array ...$arrays)
But on the call are passed 3 arguments
arraysSum([1,2,3], [4,5,6], [7,8,9])
My question is this::
Let’s say I need to define a second argument for this function as below.
function arraysSum(array ...$arrays, int numero): array
{
return array_map(function(array $array): int {
return array_sum($array);
}, $arrays);
}
$numero = 125;
print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]), $numero);
This will generate an error.
What to do to use typed language in these cases knowing that all parameters passed in the function will be summed?
There seems to be a contradiction between the number of function parameters and the number of arguments passed in the call.
I don’t quite understand it!
My goal is to do something like:
<?php
function teste( string... $_array, string a ) : array {
return array_push($_array, a);
}
print_r( teste (...["teste","2"], "adicionado") );
but without the 3 points in the ...["teste", "2"].
Is there any way?
That’s the mistake you’re making:
Parse error: syntax error, unexpected 'a' (T_STRING), expecting variable (T_VARIABLE) in /var/www/html/gasmuriae.com.br/web/gceu/teste.php on line 10
I didn’t understand the point of the question. When you set a parameter with
...
means that the number of arguments passed is variable can be 1,2,3, 10 etc.– rray
it is. So it seems that it was me who did not understand very well. The goal is for these points to reference a ttipado array of strings
– Carlos Rocha
Related: What is the name of the ... operator used in PHP 5.6? and What is the difference between parameter and argument?
– rray
In php there is no Generics hack (that language created by facebook on top of php) has.
– rray
Okay, but what would be the case if I had to pass an array of strings to the function as one of the arguments because the second parameter of the function requires a string for example? This is my difficulty.
– Carlos Rocha