Reputation: 1871
function foo($a)
{
$b = ...;
$c = ...;
return (both b and c);
}
and so I could get $b
value to $first
and $c
value to $second
I know you can return more than 1 variable by return array($b,$c)
but then it should be $var[0]
and $var[1]
and then I need to type $first = $var[0]
and $second = $var[1]
and so I'm creating more useless variables
So is it possible to do so without array?
Upvotes: 0
Views: 78
Reputation: 103
No, it can't.
But you can still return an array from function, but use "list" to accept the result for convenient:
list ($first, $second) = foo ($a);
Upvotes: 2
Reputation: 1424
The only alternative to avoid returning an array is to return an object, or serialized data, but you don't "win" something from that.
Upvotes: 0
Reputation: 5478
No, you cannot to that. Function returns only one result.
What you can do, if possible in you case, is pass a variable by reference.
function foo($a, &$b, &$c){
$b = ...;
$c = ...;
}
The following will make changes to $b and $c visible outside of the function scope.
Upvotes: 1
Reputation: 272802
Fundamentally, functions only have one return value. You could return a class with member variables first
and second
, or an associative array with keys "first"
and "second"
, but you'll still only be returning a single object.*
Alternatively, you could references to $first
and $second
into your function:
function foo($a, &$b, &$c)
{
$b = ...;
$c = ...;
}
foo(42, $first, $second);
I'm not a big fan of this approach, though, because it's not immediately clear from the call-site that $first
and $second
are going to be modified.
* Note that if you return an array, you can always use the short-hand list($first,$second) = foo(42);
.
Upvotes: 2