Any way to exit an external function from within an internal function?

In PHP, if I have one function that calls another function; is there any way to get the called function to exit the caller function without destroying the whole script?

For example, let's say I have code like:

<?php
function funcA() {
    funcB();
    echo 'Hello, we finished funcB';
}

function funcB() {
    echo 'This is funcB';
}
?>
<p>This is some text. After this text, I'm going to call funcA.</p>
<p><?php funcA(); ?></p>
<p>This is more text after funcA ran.</p>

Unfortunately, if I find something inside funcB, which is why I want to stop funcA from completing, I seem to need to exit the entire PHP script. Is there any way around this?

I understand that I could write something in funcA () to check the result from funcB (), but in my case I do not control the contents of funcA (); I only control the contents of funcB ().

; WordPress. get_template_part() WordPress / locate_template(), .

- ?

+5
4

exception funcB, funcA

+1
<?php
  function funcA() {
     try
     {
        funcB();
        echo 'Hello, we finished funcB';
     }
     catch (Exception $e) 
     {
        //Do something if funcB causes an error, or just swallow the exception
     }
  }

  function funcB() {
     echo 'This is funcB';
     //if you want to leave funcB and stop funcA doing anything else, just
     //do something like:
     throw new Exception('Bang!');
  }
?>
0

...

, , , exit(): register_shutdown_function ('shutdown'); ". - , , .

<?php
function shutdown()
{
    // This is our shutdown function, in 
    // here we can do any last operations
    // before the script is complete.

    echo 'Script executed with success', PHP_EOL;
}

register_shutdown_function('shutdown');
?>
0
source

The only way I see is to use exceptions:

function funcA() {
    funcB();
    echo 'Hello, we finished funcB';
}

function funcB() {
   throw new Exception;
   echo 'This is funcB';
}
?>
<p>This is some text. After this text, I'm going to call funcA.</p>
<p><?php  try { funcA(); } catch (Exception $e) {} ?></p>
<p>This is more text after funcA ran.</p>

Ugly, but it works in PHP5.

0
source

All Articles