dongzanxun2790 2013-01-11 16:06
浏览 127
已采纳

PHP在全局命名空间中使用类

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

If I do this:

namespace Company\Common;
use PDO;

I get this:

Fatal error: Class 'DB' not found in ...\includes\utils.php

And utils.php contains this on the error line, which worked fine before implementing namespaces:

DB::getInstance();

Alternatively I tried this:

namespace Company\Common;
class DB {
    private function __construct(){
        $this->Handle=new \PDO(...);
    }
}

Which tried to load the PDO class within our namespace as it originally did.

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?

  • 写回答

5条回答 默认 最新

  • doulu8847 2013-01-11 16:40
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探