Returning two values from a function [duplicate]
Is it possi开发者_如何学Pythonble to return two values when calling a function that would output the values?
For example, I have this:
<?php
function ids($uid = 0, $sid = '')
{
$uid = 1;
$sid = md5(time());
return $uid;
return $sid;
}
echo ids();
?>
Which will output 1
. I want to chose what to ouput, e.g. ids($sid)
, but it will still output 1
.
Is it even possible?
You can only return one value. But you can use an array that itself contains the other two values:
return array($uid, $sid);
Then you access the values like:
$ids = ids();
echo $ids[0]; // uid
echo $ids[1]; // sid
You could also use an associative array:
return array('uid' => $uid, 'sid' => $sid);
And accessing it:
$ids = ids();
echo $ids['uid'];
echo $ids['sid'];
Return an array or an object if you need to return multiple values. For example:
function foo() {
return array(3, 'joe');
}
$data = foo();
$id = $data[0];
$username = $data[1];
// or:
list($id, $username) = foo();
You can use an array and the list function to get the info easily :
function multi($a,$b) {
return array($a,$b);
}
list($first,$second) = multi(1,2);
I hope this will help you
Jerome
function ids($uid = 0, $sid = '')
{
$uid = 1;
$sid = md5(time());
return array('uid' => $uid,
'sid' => $sid
);
}
$t = ids();
echo $t['uid'],'<br />';
echo $t['sid'],'<br />';
Many possibilities:
// return array
function f() {
return array($uid, $sid);
}
list($uid, $sid) = f();
$uid;
$sid;
// return object
function f() {
$obj = new stdClass;
$obj->uid = $uid;
$obj->sid = $sid;
return $obj;
}
$obj->uid;
$obj->sid;
// assign by reference
function f(&$uid, &$sid) {
$uid = '...';
$sid = '...';
}
f($uid, $sid);
$uid;
$sid;
Pass by reference would be a solution. This way you:
return a value as you normally would
and modify the second (the one passed by refference to the function)
An example:
function foo(&$var) // notice the & in front of the parameter passed
{
$var++;
return 1;
}
$a=5;
echo foo($a);
// echoes 1, the returned value
echo $a;
// $a is now 6
return array('uid' => $uid, 'sid' => $sid);
and then access it like
$dinga = ids();
extract($dinga);
extract will make uid and sid variable. So then you can use $uid and $sid.
精彩评论