PHP OOP数据库连接使用带有类和函数的单独配置文件

rjee0c15  于 2023-04-19  发布在  PHP
关注(0)|答案(1)|浏览(80)

Dbh类未从ConfigApp类获取变量。
Everypage.php在头部:

<?php include 'config.inc.php'; ?>

config.inc.php:

<?php
class ConfigApp
{
    const dbhost = "localhost";
    const dbname = "secretdbname";
    const dbuser = "secretdbsuer";
    const dbpass = "secretdbpass";
    const var1 = "something";
    const var2 = "nothingToDoWithDB";
    const var3 = "something else else";
}
?>

dbh.class.php:

<?php
class Dbh extends ConfigApp{
    public function __construct($dbhost, $dbname, $dbuser, $dbpass) {
        $this->dbhost = $dbhost;
        $this->dbname = $dbname;
        $this->dbuser = $dbuser;
        $this->dbpass = $dbpass;
    }

    protected function connect() {
        try {
            $dsn = 'mysql:host=' .$this->$dbhost . ';dbname=' . $this->dbname;
            $pdo = new PDO($dsn, $this->dbuser,$this->dbpass);
            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            return $pdo;
            
            $dbh = new PDO('mysql:host=localhost; dbname=c1gnsoftdboop' , $dbuser, $dbpass);
            return $dbh;
        } catch (PDOException $e) {
            print "Database Connection Error!: " . $e->getMessage() . "<br/>"; 
            die(); 
        }
    }
}
?>

config.inc.php中的变量没有被传递到dbh.classes.php中。

kwvwclae

kwvwclae1#

ConfigApp类中,您定义了Class Constants,而不是属性。因此,访问它们的语法是不同的,正如文档所解释的那样。模式是:

self::constantname

所以对你来说你需要

self::dbhost

等等
现场演示:https://3v4l.org/XjCeU
因此,您在connect()中的代码将是

$dsn = 'mysql:host=' .self::dbhost . ';dbname=' . self::dbname;
$pdo = new PDO($dsn, self::dbuser, self::dbpass);

P.S. connect()函数中return $pdo;之后的所有内容都是冗余的,因为return之后的代码不能执行,而且在任何情况下都不需要定义两次连接!
此外,似乎没有必要通过Dbh类的构造函数传入新的数据库连接值,因为您打算从ConfigApp类常量中读取它们。

相关问题