我怎么能";得到“;函数的返回值


How can I "get" the return value of a function?

在方法2中要找出的语法是什么?方法1返回true还是false?

class myClass{
public function method1($arg1, $arg2, $arg3){
   if(($arg1 + $arg2 + $arg3) == 15){
      return true;
   }else{
     return false;
   }
}
public function method2(){
   // how to find out if method1 returned true or false?
}
}
$object = new myClass();
$object->method1(5, 5, 5);

要按照你的建议行事,你可以用几种方法:

1) 调用方法2 中的方法1

public function method2(){
   // how to find out if method1 returned true or false?
   if(method1($a, $b, $c))
   {
       //do something if true
   }
   else
   {
       //do something if false
   }
}

2) 在方法2之前调用它(这样做有点奇怪,但根据上下文可能需要)

$method1_result = method1($a, $b, $c);
method2($method_result);
//inside method 2 - change the constructor to take the method 1 result. e.g. method2($_method1_result)
if($_method1_result)
{
    //do something if true
}
{
    //do something if false
}

如果您只需要一次方法1的结果(因此方法1的返回值不会改变),并且将多次调用方法2,那么您可以更有效地在方法2之外执行此操作,以避免每次调用方法2时重新运行相同的代码(方法1)。

类似于:

public function method2(){
    if($this->method1(5, 5, 5) == true){
        echo 'method1 returned true';
    } else {
        echo 'method1 returned false';
    }
}
$obj = new myClass();
$obj->method2();

应导致

method1 returned true