无法打开流。仅在 __destruct() 中没有这样的文件或目录

Failed to open stream. No such file or directory only in __destruct()

我正在 class 编写 xml 文件。我想加载 __construct() 中的文件并保存 __destruct() 中的文件。但是当我在 __destruct() 中保存 xml 时出现错误 Failed to open stream. No such file or directory。但是我创建了一个手动函数 close() 并在其中保存了 xml 文件。错误消失了。 __destruct()close() 在文件处理方面有什么不同?

我的代码

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 状态:

The working directory in the script shutdown phase can be different with some SAPIs (e.g. Apache).

这意味着如果您使用文件的相对路径,它将解析为 close()__destruct() 中的不同路径。如果确实如此,您可以在 __construct() 中设置真实路径并使用它:

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);
    }
}