脚本失去了魔术方法__destruct()的权限

时间:2016-07-24 21:14:53

标签: php

我尝试在对象实例化上创建一个文件,并在对象销毁时创建另一个文件。

以下是代码:

class Foo{
    public function __construct(){
        file_put_contents('a_construct.txt', 'c');
    }
    public function __destruct(){
        file_put_contents('a_destruct.txt', 'd');
    }
}

通常会创建a_construct.txt文件。但是在创建a_destruct.txt文件时,它表现得非常奇怪。

如果我运行以下代码,那么' a_destruct'文件是否已创建。

$foo = new Foo();

我收到了这个错误:

  

警告: file_put_contents(a_destruct.txt):无法打开流:权限被拒绝

现在,如果我运行以下命令并检查文件夹,那么该文件就在那里。

$foo = new Foo();
unset($foo);

我尝试过:

  • 将名称从construct换成destruct并返回,但它始终仅适用于__construct方法;
  • 在方法上添加输出以确认它们正在被调用 - 它们是(以及两个测试代码)。

第二个测试代码向我显示我执行有权创建文件。

但第二个话题告诉我,我已经失去了'当我在脚本结束时销毁对象时的权限(因为我确保调用了该方法)。

造成这种情况的原因以及如何解决?

1 个答案:

答案 0 :(得分:5)

修复,您可以使用完整路径:

public function __destruct(){
    file_put_contents(dirname(__FILE__) . '/a_destruct.txt', 'd');
}

manual

中记录了这一点
  

脚本关闭阶段的工作目录可能与某些SAPI(例如Apache)不同。

这意味着您尝试在不同的目录中创建文件 - 以及您未获得许可的目录。

这就是为什么当你运行unset($foo)时它起作用的原因 - 因为它还没有处于关机阶段。

虽然我不建议在关机阶段处理工作目录,但我觉得可能会显示:

public function __destruct(){
    $tmp = getcwd(); // get current working dir
    chdir(dirname(__FILE__)); // set it to be same as the file
    file_put_contents('a_destruct.txt', 'd');
    chdir($tmp); // set the working dir back to what it was before
}