gpt4 book ai didi

php - 如果使用重定向,PHP5 会调用 __destruct() 吗?

转载 作者:可可西里 更新时间:2023-11-01 00:01:43 28 4
gpt4 key购买 nike

我发现如果我有以下设置,PHP5 不会调用 __destruct() 函数:

class test { __destruct() {  echo 'hehe';  exit; }}header('Location: http://test.com/');exit;

它从不调用 destruct 函数

最佳答案

destructor被称为:

  • 对于你实例化的任何对象
    • 在您发布的脚本部分,您没有实例化任何对象——也许这就是没有调用析构函数的原因?
  • 在 PHP 脚本的末尾

使用 header 进行重定向不会阻止调用析构函数。


另请注意,析构函数在 PHP 脚本的末尾被调用——但不会阻止重定向,因为 header “重定向”已经生成。

例如,使用这段代码:

class Test {
public function __destruct() {
echo 'hehe';
file_put_contents('/tmp/test-desctructor.txt', "glop\n");
exit;
}
}

$a = new Test();

header('Location: http://example.com/');
exit;

(请注意,我纠正了一些错误,并添加了该类的实际实例)

您不会在输出中看到“hehe”,但您会发现文件 /tmp/test-desctructor.txt 已创建:

$ cat /tmp/test-desctructor.txt
glop

如果您想在输出中获得“hehe”,您需要删除重定向。


生成 header 后调用析构函数——从析构函数调用 exit 不会改变 header 已经生成的事实。

哦,这是来自 manual 的注释(引用——在页面底部):

Note: Destructors called during the script shutdown have HTTP headers already sent.

这就是为什么您看不到“hehe”字符串的原因:析构函数被调用;你只是在屏幕上看不到它 ;-)

这就是我在示例中使用文件的原因,顺便说一句 ;-)

关于php - 如果使用重定向,PHP5 会调用 __destruct() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1456935/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com