简体   繁体   English

PHP-PDO连接类-无法访问

[英]PHP - PDO Connection Class - Unable To Access

I'm currently writing my first PHP application using OOP and PDO. 我目前正在使用OOP和PDO编写我的第一个PHP应用程序。 In doing so I'm working on a connection class so that I can initiate a database connection when needed. 为此,我正在研究连接类,以便可以在需要时启动数据库连接。 I believe the terms for the way I am doing it is dependency injection. 我相信我这样做的方式是依赖注入。

I currently have an error when trying to access the connection. 我目前在尝试访问连接时遇到错误。

This is my connection class: 这是我的连接类:

class db{

    private $host = '';
    private $dbname = '';
    private $username = '';
    private $password ='';  

    public $con = '';

    function __construct(){

        $this->connect();   

    }

    function connect(){

        try{

            $this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
            $this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

        }catch(PDOException $e){

            echo 'We have a problem!';

        }
    }
}

And this is how I am trying to call it inside of other classes. 这就是我试图在其他类中调用它的方式。

    private $con;

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

However this is the error I receive when trying to run it. 但是,这是我尝试运行它时收到的错误。

    Catchable fatal error: Argument 1 passed to users::__construct() must be an instance of db, none given.

Any advice on what I am doing incorrectly would be much appreciated. 对于我做错的任何建议将不胜感激。

You will need to first create your DB instance and pass it to the constructor of your 'Other' class 您将需要首先创建数据库实例,并将其传递给“ Other”类的构造函数

$db = new DB();
$class = new OtherClass($db);

Apart from that, there are other issues: 除此之外,还有其他问题:

The DB class constructor did not assign values to the database name, user and password etc. One way of doing it is to pass those settings to the constructor of DB and assign the values to the private properties. DB类的构造函数没有为数据库名称,用户和密码等分配值。一种实现方法是将这些设置传递给DB的构造函数,并将这些值分配给私有属性。

class DB{

    private $host = '';
    private $dbname = '';
    private $username = '';
    private $password ='';

    public $con = '';

    function __construct($host, $dbname, $username, $password){

        $this->host = $host;
        $this->dbname = $dbname;
        $this->username = $username;
        $this->password = $password;
        $this->connect();

    }

    function connect(){

        try{

            $this->con = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username, $this->password);
            $this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

        }catch(PDOException $e){

            echo 'We have a problem!';

        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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