我有一个使用 PDO 的 DB 包装类,在构造函数中我创建了一个 PDO 对象.包装器类在我们的命名空间中,我们使用的是自动加载器.问题是在我们的命名空间中找不到 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 CompanyCommon; class DB { private function __construct(){ $this->Handle=new PDO(...); } }有了这个,我得到了这个(正如预期的那样):
With this, I get this (as expected):
Warning: require(...vendorsCompanyCommonPDO.class.php): failed to open stream如果我这样做:
namespace CompanyCommon; use PDO;我明白了:
Fatal error: Class 'DB' not found in ...includesutils.php并且 utils.php 在错误行中包含此内容,在实现命名空间之前运行良好:
And utils.php contains this on the error line, which worked fine before implementing namespaces:
DB::getInstance();或者我试过这个:
namespace CompanyCommon; 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 上发现这也适用于别名:
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 which also applies to aliasing:
导入规则是基于每个文件的,这意味着包含的文件不会继承父文件的导入规则.
Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.
更多推荐
PHP 在全局命名空间中使用类
发布评论