简体   繁体   中英

php call a “return” from from a different 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 a "return" function from within a different function?

The purpose for this is i have a class with lots of functions.. and instead of writing a bunch of code that determines whether they should return some value, i want to simply put a function like "validate()" and have the function call a return if necessary, otherwise continue with the function.

Just wondering if it's possible to do this.

In short, NO . Thanks gosh, allowing that would make it a very weird language, where you probably would not rely on the return of any function.

You can throw exceptions, though, check out the manual . That way you can have the called methods affect the flow control in the callee -- try not overuse them to do this, though, because the code can get quite ugly with too much of this.

Here is an example on how to use exceptions for validation:

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";
    }
}

No it is not. You would have to check what b() returns, and return from a() if it is 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";
    }
}

What you are trying isn't possible. Check the manual of return

Template gap.

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

Trouble is in your mind...

如果希望a()b(1)的true return a(); true,则可以使用return a();

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