Just curious to know what the best practice would be for something like this:
A function, that returns multiple variables - how should one return these variables?
like this (globalizing):
function myfun(){
global $var1,$var2,$var3;
$var1="foo";
$var2="foo";
$var3="foo";
}//end of function
or like this (returning an array):
function myfun(){
$var1="foo";
$var2="foo";
$var3="foo";
$ret_var=array("var1"=>$var1,"var2"=>$var2,"var3"=>$var3);
return $ret_var;
}//end of function
I done a performance test, and it looks like using arrays is faster (after a few refreshes):
array took: 5.9999999999505E-6
global took: 2.0999999999938E-5
But I'm curious to know which method is the best practiced for a simple situation like this?
You should absolutely return an array. It is much clearer. You can even use the list
construct to simulate multiple return values a-la python:
function foon() {
return array('one', 'two', 'three');
}
list($one, $two, $three) = foon();
Edit: in some cases an associative array is also quite appropriate. I can't imagine the performance difference would merit this loss of clarity.