任何人都可以告诉我为什么这不起作用。
class class1 {
private $database;
function class1()
{
$database = $this->connect();
}
private function connect(){
$database = mysqli_connect("localhost","username","","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
return $database;
}
private function usedb(){
$query = "some sql";
mysqli_query($database,$query);
}
}
我希望这个简单的例子可以清楚地描述我的问题。无论如何,当我运行这样的东西时,我收到一个错误,告诉我在“usedb()”函数中有一个未定义变量“database”的引用。好像变量已超出范围......任何人都可以给我一个解决方案吗?
答案 0 :(得分:2)
这是因为在class1()
中你通过:
$database
$database = $this->connect();
设置和访问您应该使用的类的$database
属性:
$this->database = $this->connect();
同样适用于usedb()
函数:
private function usedb(){
$query = "some sql";
mysqli_query($this->database,$query);
}
所以你的最终代码应如下所示:
class class1 {
private $database;
function class1()
{
$this->database = $this->connect();
}
private function connect()
{
$database = mysqli_connect("localhost","username","","db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
return $database;
}
private function usedb()
{
$query = "some sql";
mysqli_query($this->database,$query);
}
}
注意:强>
同样适用于$database
函数中的connect()
变量。虽然名称相同,但它与外部$database
变量无关,因为应该使用$this->database
进行访问(如果需要)
答案 1 :(得分:0)
更改
$database = $this->connect();
到
$this->database = $this->connect();
并且所有$database
变量都更改为$this->database
set