Jump to content

Writing file in destructor not working


silkfire

Recommended Posts

I have a class and the last thing I want it to do is to generate a file with all the data. Unfortunately my write call never seems to run, are there any restrictions on this maybe?

If I call file_put_contents somewhere else in the code it works as usual.

 

function __destruct() {
   echo 'destruct';                                 // Called without problems
   file_put_contents('t.txt', 'eeee');      // NEVER PERFORMED, why??
}

$b = new Class // doesn't matter its name

file_put_contents('t.txt', 'eeee');                        // Works perfectly

Link to comment
https://forums.phpfreaks.com/topic/260217-writing-file-in-destructor-not-working/
Share on other sites

At the end of a script, when PHP closes handles and destroys any remaining objects, the working directory may (and probably will be) completely different from where it was during the rest of the script. That means "t.txt" won't be where you think it should be. Try looking in the main Apache directory.

 

Don't use the destructor to write files. Do it normally: make a separate function for it and call that from your script when you want it to save the file.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.