-1

I am using PHP 5.4.4 and I have a MySQL Database connection that I want to use for queries in the parent class and have that connection inherited by all children. I create a new instance of the parent and pass the db connection ($handler) as a parameter and the db connection becomes a property of the parent. When I create a new instance of a child I thought the db connection would be inherited as a property of the child, however I can only make that happen when I pass it is a parameter to both the child and parent:: constructor functions. This seems redundant to me and I am wondering what I am missing since I am new to PHP OOP.

require "pdo_connect.php"; //mysql db connection

class newUser {
    public $timestamp;
    public $dbconn;

    public function __construct($handler) { 
        $this->timestamp = time();
        $this->dbconn = $handler;
    }

    public function showdbconn() {
        //use $this->dbconn for mysql query
        print_r($this->dbconn);
    }
}

class social extends newUser {

    public function __construct($handler) {
        $this->message = 'message';
        parent::__construct($handler);
    }

    public function test() {
        //use $this->dbconn for mysql query
        print_r($this->dbconn);
    }
}

$x = new newUser($handler);
$x->showdbconn();  

$y = new social($handler); //why pass to child if passed to parent?
$y->test();
msrd0
  • 6,403
  • 9
  • 36
  • 64
user2232681
  • 809
  • 4
  • 16
  • 31
  • 2
    If you are creating two separate objects, one for parent and one for child then why would you expect them to share that in that hierarchy? When you create a `social` object and then construct `newUser` within it, then why create a separate `newUser` as well? – Hanky Panky Aug 27 '14 at 17:45
  • This is an abbreviated example. The social object will be inheriting methods from the parent which I do not show here. – user2232681 Aug 27 '14 at 17:50
  • @user2232681 , you might find this useful: http://stackoverflow.com/a/11369679/727208 – tereško Aug 27 '14 at 17:52

1 Answers1

1

Because $x is completely unrelated to $y. To see what I mean, look at this example:

$x = new newUser($handler);
$x->showdbconn();  

$z = new newUser($handler);
$z->showdbconn();

Since you have created two instances of newUser, you have to give the database connection to each one separately.

The same is true in your example. When you create a new social instance, it has to have the database connection passed to it the same way that every new newUser instance needs to have the database connection passed.

Moshe Katz
  • 13,048
  • 7
  • 58
  • 99