开发者

Is there an alternative to die?

Sorry for the dramatic sounding title, just wanted to know if there is a way to prevent all types of PHP commands from executing EXCEPT one.

For example, now when I kill a script using die() my pages look half broken because the bottom part of the page's html failed to load since it was being brought in using the include() function.

So is there a way to tell PHP "don't allow any mor开发者_运维百科e commands to be executed except the include function" ?


You can use return to "terminate" an included file, without killing the whole script:

test1.php

<?php
include 'test2.php';
echo 'foo';

test2.php

<?php
echo 'bar';
return;
echo 'baz';

Outputs:

barfoo


You're going to need to use a custom die() command, such as my_die() to include the needed files. You cannot override die() nor will any other function allow you to do what you seek.


exit() will stop execution, and run any registered exit handlers.

Throwing an exception will raise up to wherever the surrounding try is. If there is no try up to the top level, it will terminate all execution of the script.

return at global scope will return out of the current include file, back to whatever did include/require of the file.

Personally, I recommend a well-thought-out approach to exception handing, and using try/throw.


Any reason you can't just do this?

if(something didn't work) {
  include('footer.php');
  die();
}

If you're using it frequently, turn it into a function.

function finish_and_die($message) {
  print $message;
  include('footer.php');
  exit;
}


You could try something like:

if( is_secure($_GET['value']) ) // Whatever you're using to check if the value is allowed
{
    // Page content goes here
}

That way, all your other includes and page processing code will still get called.

Alternatively, if it's not valid, throw an exception, and have an exception handler that knows how to complete page code.


If you use an OOP approach combined with output buffering, this is how you can solve the problem:

The Controller class (where your logic goes) has a member which is an instance of the Template class. The Controller class has a __destruct method, which renders the Template

when exit() or die() are called, the Controller object's __destruct method is called, which in turn calls the Template object's render method.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜