Hello,

I am creating a class which creates a temporary file to write data into in __construct();

After the script is finished I'd like __destruct() to delete the temporary file.

However, I get a file not found error when the file is very clearly there. If I try and delete in the constructor it deletes fine though so I'm fairly certain it's not a path issue.

Here is my code:

<?php

class myClass
{

	private $cache;
	private $cachefile;

	public function __construct($cachef)
	{
		//create an empty cache ready for writing
		$this->cache = fopen($cachef, "w");

		//declare cachefile for class
		$this->cachefile = $cachef;
	}

	public function __destruct()
	{
		//close writing to file
		fclose($this->cache);

		//delete file
		unlink($this->cachefile);
	}

}
?>

Thanks in advance for any help.

    I tried that and it indeed should work. It is quite strange that it doesnt work. I dont know why it doesnt work for you so debug a little more 🙂

      Remember seeing this in the php manual:

      contact at tcknetwork dot com (21-Sep-2005 08:54)

      be careful while trying to access files with destruct() because the base directory (getcwd()) will be the root of your server and not the path of your script, so add before all your path called in destruct() :
      EITHER dirname($_SERVER["SCRIPT_FILENAME"])."my/path/"
      OR dirname(FILE)."my/path/"
      (be careful with includes, it will give the path of the file processed and not the main file)

      So run this on your server and see if they're different. On my test rig they're the same, but that's Windows and php5 as a cli

      $foo = new Foo();
      
      
      
      class Foo
      {
      	function __construct()
      	{
      		echo "The class: ".__CLASS__." is being constructed in ".getcwd().'<br />';
      	}
      
      
      function __destruct()
      {
      	echo "The class: ".__CLASS__." is being DESTRUCTED in ".getcwd()."<br />";
      }
      }

        Why reinvent the wheel? See [man]tmpfile[/man].

          Weedpacket;10878752 wrote:

          Why reinvent the wheel? See [man]tmpfile[/man].

          Brilliant Weedpacket, what I was looking for... I think.

          However, one flaw. This temporary file I am creating contains PHP code which I would like to be executed as PHP. ie: the class generates a PHP page using templates and then executes the created page.

          I can read the file and echo it back out no problem however I'd like to include() it if possible.

          Thanks again.

            Um, okay. If that's what you're doing.

            fread the contents of the file, and then eval("?>".$file_contents);

              A destructor cannot have parameters.
              You'd have to create a method to delete your file.

                Write a Reply...