如何不调用析构函数而退出PHP脚本? [英] How to exit a PHP script without calling the destructor?

查看:144
本文介绍了如何不调用析构函数而退出PHP脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用MVC框架和控制器,可以在析构函数中呈现页面。我正在通过php下载文件,因此在操作结束时脚本应结束。



如何在不调用析构函数的情况下结束脚本?



是否有更好的解决方案?



退出并死亡调用析构函数。



但是,如果您只是想停止由这些析构函数引起的可视输出,而不是它们可能会产生的任何其他副作用(文件关闭,数据库连接关闭),则它是最好只是杀死更多的输出,而不要把破坏者放在一边。我认为这是应该采取的方法,因为析构函数通常会出于一个重要的原因而存在:

您可以通过操作缓冲的输出来做到这一点:

p>

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

公共功能runAndBreak(){
print run。 PHP_EOL;

//如果有任何输出缓冲区正在工作,请刷新并关闭它
if(ob_get_level())ob_end_flush();

//将新缓冲区重定向到我们的devNull
ob_start(array($ this,’devNull’));
exit();
打印仍在运行;

}

函数__destruct(){
print destructor。 PHP_EOL;
}

}

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

这只会打印 run ,而不是什么在析构函数中。通过为 ob_start 提供您自己的回调例程来完成此操作然后返回输出。在本例中,我们只是通过返回一个空字符串来丢弃它。


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.

解决方案

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.

这篇关于如何不调用析构函数而退出PHP脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆