无法在 Symfony 中使用 DOMDocument
Unable to use DOMDocument in Symfony
我一直无法使用DOMDocument in symfony. After digging around, I found the problem might be that I do not have the php xml extension, but I thought that it was absurd because, despite no being able to use DOMDocument, I can use Symfony's DOMCrawler,这显然使用了类似于 DOMDocument 的东西。嗯,看了 Crawler 的源代码后,我发现他们使用了类似
$dom = new \DOMDocument('1.0', $charset);
而不是通常的
$dom = new DOMDocument('1.0', $charset);
有人知道这两者之间的区别吗?为什么在 Symfony 中一个有效而另一个无效?
因为在 symfony 中我们在每个 class 中使用命名空间。
因为您已经在 class 中声明了一个命名空间,所以您需要通知 PHP 您想要使用的每个 class 的命名空间。如果你没有声明你正在使用的 class 的命名空间,PHP 会认为这个 class 与当前的 class.
在同一个命名空间中
所以这段代码中的反斜杠 "\"
:new \DOMDocument()
是用来通知 PHP 您想要使用来自 "global" 的 DOMDocument class命名空间。
如果要使用 Datetime 对象,则在实例化 Datetime 对象时还需要使用反斜杠。
另一个解决方案是用关键字Use
声明。
例如:
use \DOMDocument;
然后在您的代码中,您将在没有反斜杠的情况下实例化:new DomDocument()
我一直无法使用DOMDocument in symfony. After digging around, I found the problem might be that I do not have the php xml extension, but I thought that it was absurd because, despite no being able to use DOMDocument, I can use Symfony's DOMCrawler,这显然使用了类似于 DOMDocument 的东西。嗯,看了 Crawler 的源代码后,我发现他们使用了类似
$dom = new \DOMDocument('1.0', $charset);
而不是通常的
$dom = new DOMDocument('1.0', $charset);
有人知道这两者之间的区别吗?为什么在 Symfony 中一个有效而另一个无效?
因为在 symfony 中我们在每个 class 中使用命名空间。 因为您已经在 class 中声明了一个命名空间,所以您需要通知 PHP 您想要使用的每个 class 的命名空间。如果你没有声明你正在使用的 class 的命名空间,PHP 会认为这个 class 与当前的 class.
在同一个命名空间中所以这段代码中的反斜杠 "\"
:new \DOMDocument()
是用来通知 PHP 您想要使用来自 "global" 的 DOMDocument class命名空间。
如果要使用 Datetime 对象,则在实例化 Datetime 对象时还需要使用反斜杠。
另一个解决方案是用关键字Use
声明。
例如:
use \DOMDocument;
然后在您的代码中,您将在没有反斜杠的情况下实例化:new DomDocument()