问题描述
我只是将网站的MySQL更改为PDO,当我尝试在其他类中使用PDO时,我遇到了一个奇怪的问题。
class Database {
private $ pdo;
public function __construct(){
$ this-> pdo = new PDO('mysql:host = localhost; dbname = appdora; charset = utf8','root','root ');
}
}
class doClass {
//变量
private $ db;
// PDO
public function __construct(Database $ db){
$ this-> db = $ db;
}
并且代码返回:以下错误:
Catchable致命错误:传递给doClass :: __ construct()的参数1必须是Database的实例,无给定,在... / index.php中调用on行xx并在第xx行上的../classes.php中定义
代码:
$ do = new doClass();
if($ do-> loginCheck()){echo'loginOk'; } else {'loginError'; }
loginCheck()是一个无类的simle函数!
你能帮我吗,有什么问题吗?
提前感谢!
$ do = new doClass
您定义了 doClass
参数:
public function __construct(Database $ db)
pre>
所以你需要提供
Database
类型的参数来成功构造对象。
例如,如果你有一个数据库对象存储在变量
$ database
之前,你可以简单地将它传递给构造函数doClass
如下:$ do = new doClass ;
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!
解决方案$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 ofdoClass
like this:$do = new doClass($database);
这篇关于PDO在其他类中有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!