2014-12-21 33 views
0

我有這樣的麻煩:在模型類中我創建了一個受保護的變量,但是在Model類的子類中,他不可用。PHP:未定義的子變量

class Model{ 

protected $db = null; 

public function __construct(){ 
    require_once 'app/classes/db.php'; 
    $db = new DB(); 
} 
} 

這是他們的孩子:

class Model_Main extends Model{ 

    public function get_data(){ 
     $db->select('news'); 
    } 
} 

錯誤:

Notice: Undefined variable: db in /var/www/localhost/htdocs/app/models/model_main.php on line 5

Fatal error: Call to a member function select() on null in /var/www/localhost/htdocs/app/models/model_main.php on line 5

+1

你可能後'$這個 - > db' – meagar

+1

第一次使用PHP OOP?只需閱讀一次文檔:http://php.net/manual/en/language.oop5.basic.php – sectus

回答

2

更改$db$this->db在這兩個類。

class Model 
{ 
    protected $db = null; 

    public function __construct() 
    { 
     require_once 'app/classes/db.php'; 
     $this->db = new DB(); 
    } 
} 

class Model_Main extends Model 
{ 
    public function get_data() 
    { 
     $this->db->select('news'); 
    } 
} 

當您未在子類中明確定義構造函數時,父類的構造函數將隱式調用。因此在這種情況下不需要parent::__constructor()調用。

更多關於構造函數:http://php.net/oop5.decon

0

$db=new DB()是在父構造,並且必須首先調用。