Search code examples
phpclassautoloader

Autoloader function tries to include a built-in PHP class


I have created a class for database manipulation. This class inherits from the PDO class.
When using that class an error appears Fatal error: Class 'app\lib\PDO' not found.
Note that I have used the backslash \ with the inheritance from PDO.

class Database extends \PDO {

    private static $object;
    private static $pdo;

    function __construct() {
        $db_config = Config::getItem('database');
        try {
            $dsn = "mysql:host=" . $db_config['db_host'] . ";dbname=" . $db_config['db_name'] . ";charset=" . $db_config['db_charset'] . "";
            parent::__construct($dsn, $db_config['db_username'], $db_config['db_password']);
        } catch (\PDOException $err) {
            trigger_error($err->getMessage(), E_USER_ERROR);
        }
    }
......

Solution

  • You have tried loading PDO in the wrong namespace. It's not in the code we are presented though. As you can see in the error Fatal error: Class 'app\lib\PDO' not found, it tries to load the PDO class in the namespace app\lib. As you probably know, it's not in that namespace.

    In order to fix that, you can put this on top of your file:

    use \PDO;
    

    Or you need to put the \ before every usage of the PDO class. To learn more about namespacing, check out the documentation.

    PDO is a "normal" class, it has a namespace declaration, if you do not load it within that namespace, it won't be found. Just like any other class. In your case, again, you have it in the app\lib namespace. So, you'll have to use the PDO class within the \PDO namespace, as that is what namespace that class is in.