doudi1979 2013-11-19 10:49
浏览 56
已采纳

PHP命名空间奇怪的行为。 再次触发调用PDO方法和__autoload?

I've following class and initPDO fails after adding setAttribute

namespace DBInterface;
class DBInterface {
    protected function initPDO() {
       $dsn = sprintf('sqlsrv:Server=%s;Database=%s', DB_SQL_SERVERNAME, DB_DB_NAME);
       $this->obPDO = new \PDO($dsn, DB_SQL_USERNAME, DB_SQL_PASSWORD);     
       $this->obPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
}

Which gives PHP error:

Could not find class file: DBInterface/PDO in root lib directory nor build lib path
Trace: [file] => path\lib\DBInterface\DBInterface.php
        [line] => 23
        [function] => __autoload
        [args] => Array
            (
                [0] => DBInterface\PDO
            )

Do you see something stupid? I can not figure it out oO. Line 23 points at setAttribute method.

  • 写回答

1条回答 默认 最新

  • dongyi6543 2013-11-19 10:51
    关注

    You just have a namespace issue. PDO exists in the root namespace, so you need a backslash at the beginning of your constants. Just like you do with new \PDO.

    $this->obPDO->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    

    Without the backslashes, PHP is looking for PDO inside your DBInterface namespace. As you can see in the error, it's look for DBInterface\PDO which doesn't exist.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部