PHP trying to use autoload function to find PDO class

autoload, namespaces, pdo, php

Solution

It's not really an autoload issue. You are attempting to call a class on the root namespace.

By the looks of it, you are in some 'Model' namespace and calling `PDO`, you must remember that namespaces are relative by default.

What you want is to either call the the absolute path:

\PDO

or at the top of your file say you're going to use PDO like this:

use PDO;

Problem

This has been bugging me for some time now and I can't seem to make sense of it. My phpinfo reports that PDO is installed and I can connect to my database on my index.php file. But when I try to open a PDO connection on a namespaced class, php is trying to use my autoload function to find PDO.php which won't work. My class is as follows: ``` abstract class { protected $DB; public function __construct() { try { $this->DB = new PDO("mysql:host=$host;port=$port;dbname=$dbname", $user, $pass); } catch(PDOException $e) { echo $e->getMessage(); } } } ``` And the error is ``` Warning: require_once((...)/Model/PDO.php): failed to open stream: No such file or directory in /(...)/Autoloader.php Fatal error: require_once(): Failed opening required 'vendor/Model/PDO.php' (include_path='.:/Applications/MAMP/bin/php/php5.4.4/lib/php') in /(...)/Autoloader.php ``` As far I as know the autoloader should be called because PHP PDO extension is installed (yes I'm completely sure). My autoload is as follows: ``` spl_autoload_register('apiv2Autoload'); /** * Autoloader * * @param string $classname name of class to load * * @return boolean */ function apiv2Autoload($classname) { if (false !== strpos($classname, '.')) { // this was a filename, don't bother exit; } if (preg_match('/[a-zA-Z]+Controller$/', $classname)) { include __DIR__ . '/../controllers/' . $classname . '.php'; return true; } elseif (preg_match('/[a-zA-Z]+Mapper$/', $classname)) { include __DIR__ . '/../models/' . $classname . '.php'; return true; } elseif (preg_match('/[a-zA-Z]+Model$/', $classname)) { include __DIR__ . '/../models/' . $classname . '.php'; return true; } elseif (preg_match('/[a-zA-Z]+View$/', $classname)) { include __DIR__ . '/../views/' . $classname . '.php'; return true; } } ``` Any help please?

Original source