Script loses resolution in the __destruct () magic method

I tried to create a file to instantiate the object and create another object to destroy the object.

Here is the code:

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

Usually a file is created a_construct.txt. But when it comes to creating a file a_destruct.txt, it behaves strangely.

If I run the following code, the file 'a_destruct' will not create .

$foo = new Foo();

And I get this error:

Warning: file_put_contents (a_destruct.txt): Could not open stream: Permission denied


Now, if I run the following and check the folder, the file is there.

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

What I tried:

  • Exchange names from constructbefore destructand back, but it always works only for the method __construct;
  • , - ( ).

, do .

, "" , script ( , ).


?

+4
1

, :

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

manual:

script SAPI (, Apache).


, - , .

, unset($foo) - .


dir , , :

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
}
+5

Source: https://habr.com/ru/post/1648970/


All Articles