我有这段代码:
<?php
class DBconnection extends Mysqli {
public $mysql;
public function __construct($host, $user, $pass, $db) {
$mysql = parent::__construct($host, $user, $pass, $db);
}
}
$mysql = new DBconnection('localhost', '**', '**', '**');
?>
但我不能在另一堂课中建立联系。
<?php
require_once('./mysqli.php');
class Activator {
private $key;
public $status;
public function __construct($key) {
$this->key = $key;
$this->status = array();
$this->activate();
}
private function activate() {
$query = $mysql->query("SELECT email, COUNT(email) AS founds FROM activation WHERE activationKey = '".$mysql->real_escape_string($this->key)."' LIMIT 1");
if($query) {
$query = $query->fetch_assoc();
if($query['founds'] == 0) {
$this->status['error'] = 'Deze code is verlopen of ongeldig.';
} else {
if($mysql->query("UPDATE users SET activation = '1' WHERE email = '".$mysql->real_escape_string($query['email'])."'")) {
$this->status['res'] = 'Uw account is geactiveerd!';
} else {
$this->status['error'] = 'Oeps, een fout! Neem contact op per email als dit over 5 minuten nog steeds zo is. Exuses voor het ongemak.';
}
}
} else {
$this->status['error'] = 'Oeps, een fout! Neem contact op per email als dit over 5 minuten nog steeds zo is. Exuses voor het ongemak.';
}
}
}
?>
我怎样才能让它发挥作用?
这是错误:
致命错误:无法在第6行的/home/raoul/domains/internetfaq.nl/public_html/dev/mysqli.php中重新声明类DBconnection
答案 0 :(得分:2)
您需要在课程中提供$mysqli
。由于范围不适用。这可以通过将其作为参数传递给activate()
方法来克服:
private function activate($mysqli) {
并致电:
$activator->activate($mysqli);
你不应该多次宣布这个课程。将该类定义放在自己的文件中,然后将该文件包含在需要它的每个页面上。
<强> DBconnection.php 强>
<?php
class DBconnection extends Mysqli {
public $mysql;
public function __construct($host, $user, $pass, $db) {
$mysql = parent::__construct($host, $user, $pass, $db);
}
}
<强> file1.php 强>
<?php
require_once('DBconnection.php');
$mysql = new DBconnection('localhost', '**', '**', '**');
?>
<强> file2.php 强>
<?php
require_once('DBconnection.php');
$mysql = new DBconnection('localhost', '**', '**', '**');
?>
有更好的方法可以做到这一点,但这会让你开始更好地组织代码。