我有2节课,我想再安排1节课。)
所以我有数据库和系统课。我希望有第三类功能。由于存在SQL查询,因此该类必须使用数据库中的函数。这就是我的结局:
class database {
public function __construct() {
$this->mysqli = new mysqli('localhost', 'root', '', 'roids');
$this->func = new functions();
}
}
class functions {
function __construct(){
$db = new database();
}
public function banned() {
$q = $db->select($this->prefix."banned", "*", "banned_ip", $this->getIP());
if (0 == 0) {
header('Location: banned.php'); // For testing
}
}
}
我这种版本以循环结束。有解决方案吗非常感谢
答案 0 :(得分:1)
您的某些类必须是源,因此其他类可能使用它的实例。
让我举个例子:
class DataBase { //THIS class is a source.
public $mysqli ;
public function __construct(){
$this->mysqli = new mysqli('localhost', 'root', '', 'roids');
$this->mysqli->set_charset("utf-8") ;
}
public function ready(){
return ($this->mysqli instanceof MySQLi && $this->mysqli->ping()) ;
}
}
class User {
protected $db;
public function __construct(DataBase $db){
$this->db = $db ; //Now you can use your source
}
public function isBanned(){
if ($this->db->ready()){
$result = $this->db->mysqli->query("SELECT id FROM banned WHERE name='Hacker' ; ") ;
return ($result && $result->num_rows >= 1) ;
}
return false ;
}
}
然后实例化源并将其提供给User的实例:
$database = new DataBase() ;
$user = new User($database) ;
现在您可以使用更复杂的功能:
if ($user->isBanned()) exit("You are banned") ;
以同样的方式创建类函数并使用它(其他类可以使用它)作为源。