简体   繁体   中英

How can I “get” the return value of a function?

What is the syntax to find out in method2 whether method1 one returned true or 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);

To do as you propose you could do it a few ways:

1) Call the method 1 inside method 2

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) Call it before method 2 (a bit weird to do it this way but possible and could be needed depending on context)

$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
}

If you are only going to need the result of method 1 ONCE (thus the return value of method 1 doesn't change) then and are going to call method 2 many times then you can be more efficient to do it outside of method 2 to save re running the same code (method 1) every time method 2 is called.

Something like:

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

$obj = new myClass();
$obj->method2();

Should result in

method1 returned true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM