Search code examples
phppdonamespacesautoload

PHP use class in global namespace


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?


Solution

  • 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.