简体   繁体   中英

PHP OOP - Database class (Undefined variable)

Learning OOP with PHP I have created a database class, but I am getting undefined variable db_host db_name db_username and db_password. I've tried with $this->db_host which removes the undefined variable for db_host but then I get a Fatal error saying "Using $this when not on object context".

<?php
class database
{
    private $db_host = "";
    private $db_username = "";
    private $db_password = "";
    private $db_name = "";

    static function connect()
    {
        try {
            new PDO("mysql:host=" . $db_host . '; dbname=' . $db_name, $db_username, $db_password);
            setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $db_error) {
            echo $db_error->getMessage();
        }
    }
}
?>

You cannot access non static instance fields from static functions (but you can access static instance fields and functions from a non static method). Moreover, you are misusing " setAttribute " function.

You should either make your instance variables static and use self keyword:

class database
{
    private static $db_host = "...";
    private static $db_username = "...";
    private static $db_password = "...";
    private static $db_name = "...";

    public static function connect()
    {
        try {
            $dbConnection = new PDO("mysql:host=" . self::$db_host . '; dbname=' . self::$db_name, self::$db_username, self::$db_password);
            $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $db_error) {
            echo $db_error->getMessage();
        }
    }
}

Or, make your function non static and relate to the class variables with $this keyword:

class database
{
    private $db_host = "...";
    private $db_username = "...";
    private $db_password = "...";
    private $db_name = "...";

    public function connect()
    {
        try {
            $dbConnection = new PDO("mysql:host=" . $this->db_host . '; dbname=' . $this->db_name, $this->db_username, $this->db_password);
            $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $db_error) {
            echo $db_error->getMessage();
        }
    }
}

What will you do with the "dbConnection" variable? Right now it doesn't serve any purpose. You should return it, or bind another instance field with it.

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