开发者

Skip the rest of the (included) file in PHP

I'm including file inner.php in outer.php, I have a condition in inner.php on which I want to stop executing inner.php but NOT the whole script, i.e. I want to jump to the first line in outer.php after the inclusion of inner.php, and I don't want to 开发者_Go百科wrap all of the code in inner.php in an if statement.

Is there a way to do this otherwise?


Just do return; or return($value); on top level of the inner.php file.

If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call.


You can just call return in your include file, but if you're having to do this then it suggests there is something wrong with your architecture. For example, consider this include file:

<?php
// include.php
echo "This is my include";
return;
echo "This is after the include";

..included on the following page:

<?php
// index.php
include('include.php');

The output you'd get is: This is my include.


How about having two files for inner. The first and the second part and place the condition on the second include?


Throw an exception on the point where you want to stop

// in inner.php:
// ...some code...

throw new Exception('Error description');

// ...some code which will not always execute...

and catch it in the file where you want to resume

// in outer.php
try {
    include 'inner.php';
} catch (Exception $e) {
    //TODO: add error handling here
}

UPDATE

Unlike using return; as other answers here suggest, using exceptions will break anywhere, even if you're in some function inside inner.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜