What's wrong with PDO in other class?

2019-08-30 14:41发布

I'm just changing my website's MySQL to PDO, and I've got a strange problem when I tried to use PDO in an other class.

class Database {
private $pdo;

public function __construct() {
    $this->pdo = new PDO('mysql:host=localhost;dbname=appdora;charset=utf8', 'root', 'root');
}
}

class doClass {

//Variables
private $db;

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

And the code is returns with: the following error:

Catchable fatal error: Argument 1 passed to doClass::__construct() must be an instance of Database, none given, called in .../index.php on line xx and defined in ../classes.php on line xx

The code:

$do = new doClass();
if ($do->loginCheck()) { echo 'loginOk'; } else { 'loginError'; }

loginCheck() is a simle function that works without classes!

Could you help me, what's the problem? Thanks in advance!

1条回答
冷血范
2楼-- · 2019-08-30 15:10
$do = new doClass();

You defined your doClass class to expect a parameter in the constructor:

public function __construct(Database $db)

So you need to supply that parameter of type Database to successfully construct the object.

For example, if you have a database object stored before somewhere inside a variable $database, you can simply pass it to the constructor of doClass like this:

$do = new doClass($database);
查看更多
登录 后发表回答