PHP OOP - 数据库类(未定义变量)

时间:2015-07-23 11:23:46

标签: php oop

使用PHP学习OOP我已经创建了一个数据库类,但是我得到了未定义的变量db_host db_name db_username和db_password。我尝试使用$ this-> db_host删除了db_host的未定义变量,但后来我得到了一个致命错误说"当不在对象上下文时使用$ this;#34;。

<?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();
        }
    }
}
?>

1 个答案:

答案 0 :(得分:1)

您无法从静态函数访问非静态实例字段(但您可以从非静态方法访问静态实例字段和函数)。而且,你滥用“setAttribute”功能。

您应该将实例变量设为静态并使用 Binding SomeBinding = new Binding (); SomeBinding.Source = SomeEntry; SomeBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; SomeBinding.Path = new PropertyPath ("Width"); SomeBinding.Mode = BindingMode.OneWay; SomeStackPanel.SetBinding (StackPanel.WidthProperty, SomeBinding); 关键字:

self

或者,使您的函数非静态,并使用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(); } } } 关键字与

的类变量相关联
$this

您将对“dbConnection”变量做什么?现在它不起任何作用。你应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(); } } } ,或用它绑定另一个实例字段。