I am making a class to writing a xml file. I want to load the file in __construct()
and save the file in __destruct()
. But I am getting an error Failed to open stream. No such file or directory
when I saving the xml in __destruct()
. But I have created a manual function close()
and save the xml file in it. error disappeared. What is the different between __destruct()
and close()
in file handling?
My Code
writemyxml.class.php:-
class writeMyXml{
protected simpleXml;
public function __construct(){
$this->simpleXml = simplexml_load_file('path/to/my/file/file.xml');
}
// Writing functions goes here... (Not deleting the file)
/*
public function close(){
$this->simpleXml->asXml('path/to/my/file/file.xml');
}
*/
public function __destruct(){
$this->simpleXml->asXml('path/to/my/file/file.xml');
}
}
test.php:-
<?php
require_once "vendor/autoloader.php";
$myxmlfile = new writeMyXml();
//Writing codes goes here
//$myxmlfile->close() Works with no errors
// Getting an error when using the __destructor() function
?>
PHP documentation states:
The working directory in the script shutdown phase can be different with some SAPIs (e.g. Apache).
This means that if you use the relative path to your file it will resolve to different paths in close()
and __destruct()
. If this is, indeed, the case you can set real path in the __construct()
and use it:
class writeMyXml
{
private $filename;
protected $simpleXml;
public function __construct($filename)
{
$this->filename = realpath($filename);
$this->simpleXml = simplexml_load_file($this->filename);
}
public function __destruct()
{
$this->simpleXml->asXml($this->filename);
}
}