Php calls a "return" from another function

function a(){ b(1); // Returns true b(0); // Echoes "Just some output" } function b($i_feel_like_it){ if($i_feel_like_it){ return return true; }else{ echo "Just some output"; } } 

Is it possible to call the return function from another function?

The purpose of this is that I have a class with many functions .. and instead of writing a bunch of code that determines whether they should return some value, I just want to put a function like validate () and a function if necessary will cause a return, otherwise it will continue to execute the function.

Just wondering if this is possible.

+4
source share
5 answers

In short, NO . Thanks, damn it, it will make this a very strange language, where you probably won’t rely on returning any function.

You can use exceptions, however check the manual . That way, you can force the called methods to influence the flow control in the called party - try not to abuse it to do this, though, since the code can get pretty ugly with too much of this.

Here is an example of using exceptions to check:

 class ValidationException extends Exception { } function checkNotEmpty($input) { if (empty($input)){ throw new ValidationException('Input is empty'); } return $input; } function checkNumeric($input) { if (!is_numeric($input)) { throw new ValidationException('Input is not numeric'); } return $input; } function doStuff() { try { checkNotEmpty($someInput); checkNumeric($otherInput); // do stuff with $someInput and $otherInput } catch (ValidationException $e) { // deal with validation error here echo "Validation error: " . $e->getMessage() . "\n"; } } 
+3
source

No, it is not. You will need to check what b () returns, and return from a (), if true.

 function a() { if (b(1) === true) return true; // Makes a() return true if (b(0) === true) return true; // Makes a() echo "Just some output" } function b($i_feel_like_it) { if ($i_feel_like_it){ return true; } else { echo "Just some output"; } } 
+2
source

What you are trying is impossible. Check back user manual

+1
source

Clearance pattern.

 function a() { b(); return $a; } function b() { c(); return $b; } 

The problem is in your mind ...

0
source

If you want a() return true from b(1) true, you can use return a();

0
source

Source: https://habr.com/ru/post/1487582/


All Articles