问题描述
有人帮我找出下面的代码有什么问题吗? 我有 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;
}
}
?>
返回结果
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();
}
}