有可能有一个函数有两个返回值,像这样:
function test($testvar)
{
// Do something
return $var1;
return $var2;
}
如果是这样,我怎样才能分别得到每一个回报?
有可能有一个函数有两个返回值,像这样:
function test($testvar)
{
// Do something
return $var1;
return $var2;
}
如果是这样,我怎样才能分别得到每一个回报?
当前回答
没有办法返回两个变量。虽然,你可以传播一个数组并返回它;创建一个条件返回一个动态变量,等等。
例如,这个函数将返回$var2
function wtf($blahblah = true) {
$var1 = "ONe";
$var2 = "tWo";
if($blahblah === true) {
return $var2;
}
return $var1;
}
在应用程序:
echo wtf();
//would echo: tWo
echo wtf("not true, this is false");
//would echo: ONe
如果你两个都想要,你可以稍微修改一下函数
function wtf($blahblah = true) {
$var1 = "ONe";
$var2 = "tWo";
if($blahblah === true) {
return $var2;
}
if($blahblah == "both") {
return array($var1, $var2);
}
return $var1;
}
echo wtf("both")[0]
//would echo: ONe
echo wtf("both")[1]
//would echo: tWo
list($first, $second) = wtf("both")
// value of $first would be $var1, value of $second would be $var2
其他回答
你可以通过引用来设置两个或多个变量的值:
function t(&$a, &$b) {
$a = 1;
$b = 2;
}
t($a, $b);
echo $a . ' ' . $b;
输出:
1 2
或者你可以通过引用传递:
function byRef($x, &$a, &$b)
{
$a = 10 * $x;
$b = 100 * $x;
}
$a = 0;
$b = 0;
byRef(10, $a, $b);
echo $a . "\n";
echo $b;
这将输出
100
1000
是的,你可以使用对象:-)
但最简单的方法是返回一个数组:
return array('value1', 'value2', 'value3', '...');
这是最简单的方法:
public function selectAllUsersByRole($userRole, $selector) {
$this->userRole = $userLevel;
$this->selector = $selector;
$sql = "SELECT * FROM users WHERE role <= ? AND del_stat = 0";
$stm = $this->connect()->prepare($sql); // Connect function in Dbh connect to database file
$stm->execute([$this->userRole]); // This is PHP 7. Use array($this->userRole) for PHP 5
$usersIdArray = array();
$usersFNameArray = array();
$usersLNameArray = array();
if($stm->rowCount()) {
while($row = $stm->fetch()) {
array_push($usersIdArray, $row['id']);
array_push($usersFNameArray, $row['f_name']);
array_push($usersLNameArray, $row['l_name']);
// You can return only $row['id'] or f_name or ...
// I used the array because it's most used.
}
}
if($this->selector == 1) {
return $usersIdArray;
}elseif($this->selector == 2) {
return $usersFNameArray;
}elseif($this->selector == 3) {
return $usersLNameArray;
}
}
我们如何调用这个函数呢?
$idData = $selectAllUsers->selectAllUsersByLevel($userRole, 0);
print_r($idData);
$idFName = $selectAllUsers->selectAllUsersByLevel($userRole, 1);
print_r($idFname);
就是这样。非常容易。
在你的例子中,第二次返回永远不会发生——第一次返回是PHP运行的最后一件事。如果你需要返回多个值,返回一个数组:
function test($testvar) {
return array($var1, $var2);
}
$result = test($testvar);
echo $result[0]; // $var1
echo $result[1]; // $var2