Search code examples
phpfunctionscopereturn

Execute return as function caller


Is there a way to execute a return statement as a function's caller? Take:

index.php:

require action.php

action.php:

require check.php
checkAccess() || return;
doSomeSecretStuff();

check.php:

function checkAccess() {
    if(loggedIn)
        return true;
    return false;
}

and I was wondering if there is a way to execute that return statement forcing action.php to stop from inside checkAccess()?

kinda like get_function_caller().eval("return");

(super-pseudo code)


Solution

  • If you have this:

    check();
    foo();
    

    There is no way that check could return for you, so it's guaranteed that foo will be executed. And that's a good thing, otherwise you'd have no guarantees about your execution flow in your code.

    The only way this may skip the execution of foo is if a fatal error occurred in check and everything halts, or—and here it comes—if check throws an exception.

    You'd use this something like this:

    let foo = false;
    
    function assertFoo() {
      if (!foo) {
        throw new Error('Not enough foo');
      }
    }
    
    function bar() {
      assertFoo();
      console.log('Barrr!');
    }
    
    try {
      bar();
    } catch (e) {
      console.log(e.message);
    }