问题描述
我有一个使用PDO的数据库包装器类,并在构造函数中创建了一个PDO对象. wrapper类位于我们的名称空间中,并且正在使用自动加载器.问题在于,在我们的命名空间中找不到PDO类,因此我尝试按照.
I have a DB wrapper class that uses PDO and in the constructor I create a PDO object. The wrapper class is in our namespace and we are using an autoloader. The issue is that the PDO class cannot be found within our namespace, so I tried using the global namespace as described here.
//Class file
namespace Company\Common;
class DB {
private function __construct(){
$this->Handle=new PDO(...);
}
}
有了这个,我得到了(如预期的那样):
With this, I get this (as expected):
Warning: require(...\vendors\Company\Common\PDO.class.php): failed to open stream
如果我这样做:
namespace Company\Common;
use PDO;
我明白了:
Fatal error: Class 'DB' not found in ...\includes\utils.php
并且utils.php在错误行中包含此代码,在实现名称空间之前可以正常工作:
And utils.php contains this on the error line, which worked fine before implementing namespaces:
DB::getInstance();
或者我尝试了这个:
namespace Company\Common;
class DB {
private function __construct(){
$this->Handle=new \PDO(...);
}
}
哪个试图像最初那样在我们的命名空间中加载PDO类.
Which tried to load the PDO class within our namespace as it originally did.
我该如何解决?我以为通过执行use PDO
或new \PDO
它将加载全局PDO类,但是它似乎不起作用?
How can I resolve this? I thought by doing use PDO
or new \PDO
it would load the global PDO class, but it doesn't seem to be working?
推荐答案
已解决.我没有意识到,别名空间仅适用于当前文件,不适用于将来包含的任何文件.在PHP.net上发现了这一点,它也适用于别名:
Solved it. I didn't realize that aliasing a namespace only applies to the current file, and not any future included files. Found this on PHP.net which also applies to aliasing:
这篇关于PHP在全局名称空间中使用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!