我在PHP中有2个类我希望彼此使用,但是在2个不同的PHP脚本中的类,如clothing_product.php和database.php。它看起来像下面这样:
database.php中:
require_once('config.php');
class MySqlDatabase
{
private $connection;
private $last_query;
private $magic_quotes_active;
private $real_escape_string_exist;
function __construct(){
$this->open_connection();
$this->magic_quotes_active = get_magic_quotes_gpc();
$this->real_escape_string_exist = function_exists("mysql_real_escape_string");
}
private function open_connection()
{
$this->connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$this->connection){
die("Connection failed!". mysql_error());
}
else{
$db_select = mysql_select_db(DB_NAME);
if(!$db_select){
die("Select database failed". mysql_error());
}
}
}
public function query($sql){
$this->last_query = $sql;
$result = mysql_query($sql,$this->connection);
$this->confirm_query($result);
return $result;
}
public function confirm_query($result){
if(!$result){
$output = "Database query failed: " . mysql_error()."<br /><br />";
$output.= "Last query that fail is:" . $this->last_query;
die($output);
}
}
private function escape_value($value) {
if ($this->real_escape_string_exist) {
if($this->magic_quotes_active) {$value = stripslashes($value);}
$value = mysql_real_escape_string($value);
}
else {
if (!$this->magic_quotes_active) {$value = addslashes($value);}
}
return $value;
}
public function fect_array($result){
return mysql_fetch_array($result);
}
public function num_rows($result){
return mysql_num_rows($result);
}
public function last_id(){
return mysql_insert_id($this->connection);
}
public function affected_rows(){
return mysql_affected_rows($this->connection);
}
public function close_connection(){
if(isset($this->connection)){
mysql_close($this->connection);
unset($this->connection);
}
}
}
//$db = new MySqlDatabase();
clothing_product.php:
包括( '../ database.php中');
class Clothing_Product {
public $db = new MySqlDatabase();
public static function test(){
echo "Static call successfull";
return "Static call successfull";
}
}
问题是当我尝试使用'Public $ db = new MySqlDatabase();'在课堂服装_产品我得到错误。我认为问题可能是我打错了电话。请帮我一个菜鸟。
答案 0 :(得分:2)
您无法将成员变量初始化为非静态的任何内容,并且您尝试在此处创建对象:
public $db = new MySqlDatabase();
来自the manual:
这个声明可能包括初始化,但是这个 初始化必须是一个常量值 - 也就是说,它必须能够 在编译时进行评估,不得依赖于运行时 信息以便进行评估。
解决方法是在构造函数中设置变量:
public $db;
public function __construct() {
$this->db = new MySqlDatabase();
}