![](/img/trans.png)
[英]How to get different outcomes of two variables being different percentage to eachother
[英]how can i get two classes to interact with eachother
我想從另一個類實現一個類,但是當我嘗試在類foo中調用db的函數時,它會失敗,除非我使用新的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行有一個未定義的變量db,並在非對象上調用成員函數query()。
而不是$db
,你應該使用$this->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();
}
}
需要通過$this
引用PHP成員變量
class foo {
private $db;
public function __construct() {
$this->db = new db();
}
public function update(){
$this->db->query();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.