Search code examples
phppdonamespacesspl-autoload-register

SPL_AUTOLOAD_REGISTER overriding PHP Extensions


I've written a quick autoloading script for php, although it seems as though the autoloading is overriding php extensions and such.

I'm creating a database class for pdo, and I need to implement PDO within the class. The issue with this is that PHP thinks that PDO is a class located in the same namespace as my database class.

index.php;

use database\db;
require_once "core/inc.php";
$db = DB::instance();

core/inc.php;

spl_autoload_register(function($a) {
    $file;
    if(file_exists($file = dirname(__DIR__) . DIRECTORY_SEPARATOR . "module" . DIRECTORY_SEPARATOR . str_replace("\\", DIRECTORY_SEPARATOR, strtolower($a)) . ".php"))
        require_once $file;
});

module/database/db.php;

namespace database;
$this->_pdo = new PDO('mysql:host=' . $config->get('database/ip') . ';dbname=' . $config->get('database/db'), $config->get('database/un'), $config->get('database/pw'));

I haven't really touched namespaces before in PHP, so I cannot find a viable solution around this. I've been researching quite a bit and trying to find a fix, although I have yet to succeed in that task.

Any help would be appreciated,
Cheers.


Solution

  • Tell your code that PDO is in the global (\) namespace, not in the specified namespace

    namespace database;
    $this->_pdo = new \PDO('mysql:host=' . $config->get('database/ip') . ';dbname=' . $config->get('database/db'), $config->get('database/un'), $config->get('database/pw'));