How to exit a PHP script without calling the destructor?

♀尐吖头ヾ 提交于 2019-12-11 09:32:32

问题


Working with an MVC framework and the controller renders the page in the destructor. I am downloading a file through php, so at the end of the action the script should end.

How to end the script without calling the destructor?

Is there a better solution?

exit and die call the destructor.


回答1:


As David said: you'll need to call exit() inside a destructor to stop it.

If however you just want to halt the visual output caused by these destructors but not any other side-effects (file closing, database connection closing) they might do, then it's best to just kill the further output but leave the destructors alone. Which in my opinion would be the route to take since destructors tend to be there for one important reason: cleaning up.

you can do that by manipulating buffered output:

<?php
class Tester{
   public function devNull($string){
       return "";
   }

   public function runAndBreak(){
        print "run" . PHP_EOL;

        // if any output buffer is working, flush it and close it
        if(ob_get_level()) ob_end_flush();

        // redirect new buffer to our devNull
        ob_start(array($this,'devNull'));
        exit();
        print "still running";

   }

   function __destruct(){
        print "destructor" . PHP_EOL;
   }

}

$t = new Tester();
$t->runAndBreak();

this will only print run and not what's in the destructor. It's done by giving your own callback routine to ob_start that handles and then returns the output. In our case here we simply discard it by returning an empty string.




回答2:


See this answer. Try creating a destructor in the class that downloads the file that checks if a file was indeed sent to the browser, and if so, call exit() in that destructor.




回答3:


This will certainly stop your script but be careful, if you run such a server where one process serves several PHP requests those will stop as well:

$pid = getmypid();
exec("kill $pid");
exec("TSKILL $pid");


来源:https://stackoverflow.com/questions/11302226/how-to-exit-a-php-script-without-calling-the-destructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!