摘要中的 Db 连接错误 class - 有人帮我找到错误吗?
Db connect error in abstract class - anybody help me to find the bug?
有人帮我看看下面的代码有什么问题吗?
我有 class student.php extends db.php.
Student.php
<?php
require_once('db.php');
class Student extends Db {
public function __construct() {
$res = $this->db_connect();
}
}
$result = new Student();
db.php
<?php
abstract class Db {
protected $db_host;
protected $db_user;
protected $db_password;
protected $db_name;
public function __construct() {
$this->db_host = 'localhost';
$this->db_user = 'root';
$this->db_password = '';
$this->db_name = 'student';
}
protected function db_connect() {
if(!isset($GLOBAL['db_connection'])) {
$GLOBAL['db_connection'] = new mysqli($this->db_host, $this->db_user, $this->db_password, $this->db_name);
}
if(mysqli_connect_errno()) {
$responseArray['status'] = '500';
$responseArray['response'] = 'Error'. mysqli_connect_error().' Error No: '. mysqli_connect_errno();
}
else {
$responseArray['status'] = '200';
$responseArray['response'] = 'Database connection success';
}
return $responseArray;
}
}
?>
它returns结果
mysqli::__construct(): (HY000/1045): Access denied for user ''@'localhost' (using password: NO)
我知道数据库变量是空的,这就是我收到错误的原因。但我需要确定代码有什么问题。
您已覆盖 __construct()
方法,因此未设置默认值。
检查这个:
<?php
require_once('db.php');
class Student extends Db {
public function __construct() {
// call Db's constructor
parent::__construct();
$res = $this->db_connect();
}
}
有人帮我看看下面的代码有什么问题吗? 我有 class student.php extends db.php.
Student.php
<?php
require_once('db.php');
class Student extends Db {
public function __construct() {
$res = $this->db_connect();
}
}
$result = new Student();
db.php
<?php
abstract class Db {
protected $db_host;
protected $db_user;
protected $db_password;
protected $db_name;
public function __construct() {
$this->db_host = 'localhost';
$this->db_user = 'root';
$this->db_password = '';
$this->db_name = 'student';
}
protected function db_connect() {
if(!isset($GLOBAL['db_connection'])) {
$GLOBAL['db_connection'] = new mysqli($this->db_host, $this->db_user, $this->db_password, $this->db_name);
}
if(mysqli_connect_errno()) {
$responseArray['status'] = '500';
$responseArray['response'] = 'Error'. mysqli_connect_error().' Error No: '. mysqli_connect_errno();
}
else {
$responseArray['status'] = '200';
$responseArray['response'] = 'Database connection success';
}
return $responseArray;
}
}
?>
它returns结果
mysqli::__construct(): (HY000/1045): Access denied for user ''@'localhost' (using password: NO)
我知道数据库变量是空的,这就是我收到错误的原因。但我需要确定代码有什么问题。
您已覆盖 __construct()
方法,因此未设置默认值。
检查这个:
<?php
require_once('db.php');
class Student extends Db {
public function __construct() {
// call Db's constructor
parent::__construct();
$res = $this->db_connect();
}
}