2015-05-27 23 views
0

這是我的代碼看起來像:當我複製global $wpdb;get_pagination()功能如何在同一個類中運行所有函數的代碼?

Fatal error: Call to a member function get_var() on a non-object

,那我就不:

public function __construct() { 
    global $wpdb; 
} 

private function get_pagination() { 
    $user_count = $wpdb->get_var("SELECT COUNT(*) FROM yc_customers WHERE $this->get_where"); 
} 

當我運行它,我會得到這個錯誤得到任何錯誤。儘管如此,我不想將它複製到我的所有功能中。爲什麼我得到這個錯誤,即使我在__construct函數中有global $wpdb

回答

1

如果你想使用global,你不希望它,那麼你可以這樣做:

private function get_pagination() { 
    global $wpdb; 
    $user_count = $wpdb->get_var("SELECT COUNT(*) FROM yc_customers WHERE $this->get_where"); 
} 

但是你可以簡單地傳遞變量在構造函數中,如:

public function __construct($wpdb) { 
    $this->wpdb = $wpdb; 
} 

private function get_pagination() { 
    $user_count = $this->wpdb->get_var("SELECT COUNT(*) FROM yc_customers WHERE $this->get_where"); 
} 

尋找「依賴注入」。

相關問題