-2

In the basic example below I'm expecting that the one() method terminates the two() method when the if statements returns true, but it always returns 'something'. How can I terminate the execution of method two() from method one()?

Class MYclass {

    // This method must ends two()
    private function one($var){
       
       if( $var == 'value' ) {
         return;
       }
    
    }

    public function two(){

       $this->one('value'); // if parameter is 'value' this must ends here 
    
       return 'something'; // else it will return something
    }

}

$three = new Myclass;

echo $three->two(); // This outputs 'something' but I'm expecting nothing

silvered.dragon
  • 407
  • 1
  • 7
  • 19
  • 1
    Make method one return a value to indicate what should happen, and have method two check that returned value before deciding what to do next – ADyson Sep 02 '22 at 11:13
  • 1
    Your phrasing is a bit misleading here, _"Terminate method execution"_ makes it sound as if you wanted to interfere with a method that currently _is_ running (like executing a loop with longer runtime), but it appears you actually just want a method to do different things, based on a criterion determined by a different method call. – CBroe Sep 02 '22 at 11:15
  • 1
    Method `two()` will always return `something` because its coded to always return `something` Step 1: bench check you logic, ...... Step 10: come to SO – RiggsFolly Sep 02 '22 at 11:20

1 Answers1

4

Let method one() to return really-something (like a boolean true|false) then check what is returned. For example:

Class MYclass {

    // This method must ends two()
    private function one($var){
       
       if( $var == 'value' ) {
         return true;
       }
       return false;  // else return false

    }

    public function two(){

       if ($this->one('value')) {
          return ;
       }
       return 'something'; // else it will return something
    }

}
Geo Halkiadakis
  • 370
  • 1
  • 7
  • 1
    It might be worth mentioning that, in PHP in particular, `return;` is equivalent to `return null;` and so the reason you get no output when you call `echo $three->two();` is that `echo null;` doesn't output anything. – IMSoP Sep 02 '22 at 11:29
  • Ok this was my initial solution, but What if the return of one() Is a real value? Do I have to repeat like this `if ($this->one('value')) { return $this->one('value'); }` it's a Little annoying – silvered.dragon Sep 02 '22 at 11:49
  • 1
    Probably something like this is best one line solution `if( $one = $this->one($request) ) return $one;` – silvered.dragon Sep 02 '22 at 13:15
  • yup! that was what I wanted to write... (otherwise it will now return always nothing) – Geo Halkiadakis Sep 02 '22 at 13:36