0
votes

I have this trouble: in Model class me create a protected variable, but in child of Model class, he is not available.

class Model{

protected $db = null;   

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

This is their child:

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

Error:

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

2
You're probably after $this->db - meagar♦
First time with PHP OOP? Just read once documentation about: php.net/manual/en/language.oop5.basic.php - sectus

2 Answers

3
votes

Change $db to $this->db in both classes.

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');
    }
}

When you don't explicitly define a constructor in the child class, the parent's constructor is called implicitly. So the parent::__constructor() call is not needed in this case.

More on constructors: http://php.net/oop5.decon

1
votes

The $db=new DB() is in the parent constructor and that has to be called first.