简体   繁体   中英

Isntance of PDO given instead of namespace name - PSR4 Autoloading with composer

I am trying to learn how to use PDO. I have a very small application that uses namespaces. I use composer to autoload the classes.

I am trying to follow PHPTheRightWay MVC approach to PDO but I am failing. I have setup my DbModel class to match their one and in my php code I create a new instance of it and parse the PDO object.

Class:

namespace Acme;

class DbModel {

    protected $db;

    public function __construct(PDO $db)
    {
        $this->db = $db;
    }

    public function getAllPlayers()
    {
        return $this->db->query('SELECT * FROM player');
    }
}

Page:

use Acme\DbModel;
use Acme\Player;
use Acme\Team;
use Acme\Match;

$db = new PDO('mysql:host=127.0.0.1;dbname=football', 'root', '');
$model = new DbModel($db);

However, I get the following error. I have no idea why this is happening.

Catchable fatal error: Argument 1 passed to Acme\\DbModel::__construct() must be an instance of Acme\\PDO, instance of PDO given, called in C:\\xampp\\htdocs\\footballMatch\\matchDay.php on line 9 and defined in C:\\xampp\\htdocs\\footballMatch\\src\\DbModel.php on line 9

After adding this class I run composer install and composer dump-autoload .

Add the root namespace prefix to PDO wherever it's used, eg:

public function __construct(\PDO $db)

For now, your script assumes that the class named PDO should be under the Acme namespace, which isn't the case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM