我制作了2个php文件:
这个文件我用来连接数据库......但是我收到了错误...
你可以帮帮我..class.database.php:
<?php
include_once ( '../config.php' );
class database {
protected $db_conn;
public $db_name = DB_NAME;
public $db_host = DB_HOST;
public $db_user = DB_USER;
public $db_pass = DB_PASS;
}
function connect(){
try {
$this->db_conn = new PDO("mysql:host = $this->db_host;dbname=$this->db_name",$this->db_user,$this->db_pass);
return $this->db_conn;
} catch(PDOException $e) {
return $e->getMessage();
}
}
?>
class.ManageDatabase.php:
<?php
class ManageDatabase{
public $link;
function __construct(){
include_once( 'class.database.php' );
$conn = new database;
$this->link = $conn->connect();
return $this->link;
}
}
$something = new ManageDatabase;
echo $something;
?>
和错误:
Fatal error: Call to undefined method database::connect() in C:\xampp\htdocs\myweb\crud\core\class.ManageDatabase.php on line 9
答案 0 :(得分:3)
将connect函数放在Database类中,而不是放在它中(在此文件中:class.database.php)
答案 1 :(得分:0)
函数connect在类数据库
之外定义class database {
protected $db_conn;
public $db_name = DB_NAME;
public $db_host = DB_HOST;
public $db_user = DB_USER;
public $db_pass = DB_PASS;
// don't close the class here
function connect(){
try {
$this->db_conn = new PDO("mysql:host = $this->db_host;dbname=$this->db_name",$this->db_user,$this->db_pass);
return $this->db_conn;
} catch(PDOException $e) {
return $e->getMessage();
}
}
} //close it here
答案 2 :(得分:0)
...简单 你必须改变这个:
class database {
protected $db_conn;
public $db_name = DB_NAME;
public $db_host = DB_HOST;
public $db_user = DB_USER;
public $db_pass = DB_PASS;
}
function connect(){
try {
$this->db_conn = new PDO("mysql:host = $this->db_host;dbname=$this->db_name",$this->db_user,$this->db_pass);
return $this->db_conn;
} catch(PDOException $e) {
return $e->getMessage();
}
}
到
class database {
protected $db_conn;
public $db_name = DB_NAME;
public $db_host = DB_HOST;
public $db_user = DB_USER;
public $db_pass = DB_PASS;
function connect(){
try {
$this->db_conn = new PDO("mysql:host = $this->db_host;dbname=$this->db_name",$this->db_user,$this->db_pass);
return $this->db_conn;
} catch(PDOException $e) {
return $e->getMessage();
}
}
}
你在函数之前关闭了你的类,所以当你在类中调用函数时,它没有工作。
答案 3 :(得分:0)
你的连接功能应该是班级的一种方法:
class database {
protected $db_conn;
public $db_name = DB_NAME;
public $db_host = DB_HOST;
public $db_user = DB_USER;
public $db_pass = DB_PASS;
function connect(){
try {
$this->db_conn = new PDO("mysql:host = $this->db_host;dbname=$this->db_name",$this->db_user,$this->db_pass);
return $this->db_conn;
} catch(PDOException $e) {
return $e->getMessage();
}
}
}