PHP 在全局命名空间中使用类 [英] PHP use class in global namespace

查看:31
本文介绍了PHP 在全局命名空间中使用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 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 PDOnew 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:

导入规则是基于每个文件的,这意味着包含的文件不会继承父文件的导入规则.

Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.

这篇关于PHP 在全局命名空间中使用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆