从PHP函数中获取返回值


Getting return values from function PHP

如何在PHP中的另一个函数中调用函数返回值。

例如,我有这样一个函数:

function doSomething($var) {
   $var2 = "someVariable";
   doSomethingElse($var2);
}
function doSomethingElse($var2) {
   // do anotherSomething 
   if($anotherSomething) {
    echo "the function ran";
    return true;
   }
   else {
     echo "there was an error";
     return false;
   }
}

我想在第一个函数内部回显第二个函数的回显。原因是当第二个函数失败时,它可以产生一个字符串,而第一个函数不能。

那么我如何输出第二个函数的返回值呢?

创建一个包含您想要返回的值的数组,然后返回该数组。

function doSomethingElse($var2) {
   // do anotherSomething 
   if($anotherSomething) {
    $response['message'] = "the function ran";
    $response['success'] = TRUE;
   }
   else {
     $response['message'] = "there was an error";
     $response['success'] = FALSE;
   }
    return $response;
}

在你的其他函数

$result = doSomethingElse($var2); 
echo $result['message'];`