英文:
PHP OOP Database Connection using Seperate Config File with Clasess and functions
问题
The issue is that variables from config.inc.php
are not being passed into dbh.class.php
.
英文:
The class Dbh is not getting the variables from class ConfigApp.
Everypage.php in the head:
<?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();
}
}
}
?>
Variables from config.inc.php are not being passed into dbh.classes.php.
答案1
得分: -1
在ConfigApp
类中,您已经定义了类常量,而不是属性。因此,访问它们的语法与文档中所解释的不同。模式是:
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);
附言:在connect()
函数中的return $pdo;
之后的所有内容都是多余的,因为在return
之后无法执行代码,并且无论如何,您不需要定义两次连接!
此外,似乎没有必要通过Dbh
类的构造函数传递新的数据库连接值,因为您打算从ConfigApp
类常量中读取它们。
英文:
In the ConfigApp
class you've defined Class Constants, not properties. Therefore the syntax to access them is different, as that documentation explains. The pattern is:
self::constantname
So in your case, you'd need
self::dbhost
etc.
Live demo: https://3v4l.org/XjCeU
Therefore your code in connect()
would be
$dsn = 'mysql:host=' .self::dbhost . ';dbname=' . self::dbname;
$pdo = new PDO($dsn, self::dbuser, self::dbpass);
P.S. Everything after return $pdo;
in the connect()
function is redundant, since code after a return
cannot be executed, and in any case you don't need to define the connection twice!
Also, there seems to be no need to pass in new database connection values through the constructor of the Dbh
class, since you're intending to read them from the ConfigApp
class constants.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论