Goodday,
我收到一个奇怪的错误。
这是我的代码:
<?php
$con=mysqli_connect("localhost","root","","testdatabase");
class database{
public function select($tableName){
$result = mysqli_query($con,"SELECT * FROM ".$tableName);
}
}
$database = new database();
?>
错误消息是$ con是一个未定义的变量。但我在第2行定义$ con?
当我有var_dump con时它也会说NULL。
我做错了什么?
答案 0 :(得分:3)
如果要访问方法或函数中的$ con var,则必须在代码中对其进行全局化:
public function select($tableName){
global $con;
$result = mysqli_query($con,"SELECT * FROM ".$tableName);
}
但是你不应该那样做,全局性是邪恶的!
这就是您的代码应该如何:
<?php
class database{
protected $con;
public function __construct($host, $user, $password, $dbname){
$this->con = mysqli_connect($host, $user, $password, $dbname);
}
public function select($tableName){
$result = mysqli_query($this->con,"SELECT * FROM ".$tableName);
}
}
$database = new database("localhost", "root", "", "testdatabase");
?>
答案 1 :(得分:1)
连接$con
在全局范围内可用。您可能想要做的是在Database对象的构造函数中注入mysql连接(以mysqli对象的形式)。这是一个简单的例子:
<?php
$mysqli= new mysqli("localhost","root","","testdatabase");
class database{
protected $mysqli = null;
public function __contruct(MySQLI $mysqli = NULL) {
$this->mysqli = $mysqli;
}
public function select($tableName){
$result = $this->mysqli->query("SELECT * FROM ".$tableName);
}
}
$database = new database($mysqli);
?>
请注意,既然您正在尝试使用面向对象的范例,那么您也可以以面向对象的方式使用mysqli。
答案 2 :(得分:1)
您不能在类中使用全局变量。
<?php
class database {
private $con;
public $result;
public function select($tableName){
$this->con = mysqli_connect("localhost","root","","testdatabase");
$this->result = mysqli_query($this->con,"SELECT * FROM ".$tableName);
}
}
$database = new database();
// do something with result
if($database->result) {
echo "Query returned something!";
}
?>
答案 3 :(得分:0)
在你的类中添加一个构造函数,并在这个函数中声明你的连接。
class database{
private $con;
public function __construct(){
$this->con=mysqli_connect("localhost","root","","testdatabase");
}
public function select($tableName){
$result = mysqli_query($this->con,"SELECT * FROM ".$tableName);
}
}
$database = new database();