1
class bm_main {

    public $db;

    public function __construct(){

        $this->db = new db();
    }

}

class bm extends bm_main{

    public function __construct($id){
        $this->db = parent::$db;
            $this->db->save($id);
    }
}

How to access the $db object from parent class so i can use it in the child one

1 Answer 1

4

Call the parent constructor so the db class is instantiated:

    public function __construct($id) {
        parent::__construct();
        $this->db->save($id);
    }

The $db property is inherited by the subclass, and is public, so you can access it using $this->db.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you but i can't do this because parent constructor calls other methods that i won't call any other suggestions
@Stasa: -rolls eyes- you could have said so... move your $this->db = new db(); to its own method and have your parent and child constructors call that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.