我想从另一个类中实例化一个类,但是当我尝试在类 foo 中调用 db 函数时,它会失败,除非我声明 new db() 并在同一个函数中调用该函数
class foo {
private $db;
public function __construct() {
$db = new db();
// if i call $db->query(); from here it works fine
}
public function update(){
$db->query();
}
}
class db {
public function __construct() {
}
public function query(){
echo "returned";
}
}
$new_class = new foo();
$new_class->update();
这段代码给我一个错误,说我在第 7 行有一个 undefined variable db 并调用了一个非对象上的成员函数 query()。
最佳答案
您应该使用 $this->db
而不是 $db
。
在你的代码中,$db
是 __construct
函数的局部变量,
public function __construct() {
$db = new db();
// $db is only available within this function.
}
而你想把它放到成员变量中,所以你需要使用$this
,
class foo {
private $db; // To access this, use $this->db in any function in this class
public function __construct() {
$this->db = new db();
// Now you can use $this->db in any other function within foo.
// (Except for static functions)
}
public function update() {
$this->db->query();
}
}
关于php - 我怎样才能让两个类相互交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16493053/