AlexHeuman
AlexHeuman

Reputation: 1006

PHP inheritance concerning mysqli

I've created a class named Database.

class Database extends mysqli {

    public function __construct() {
        parent::__construct();
        $mysqli = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBDATABASE);

        if (mysqli_connect_errno()) {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }
    }   
}

And a class called Model that extends Database

class Model {

    function __construct() {
        $this->db = new Database();        
    }
}

And a class registerModel that extends Model

class registerModel extends Model {

    public function __construct() {
        echo "This is the register Model";
    }

    public function register(//VARIOUS PASSED VALUES) {
        **$stmt = $mysqli->prepare("INSERT INTO users (firstName, lastName) values (?, ?)");**
        ...
        ... More Code
        ...

    }

What I'm trying to do is get the $mysqli from the original Database class, but I'm unsure how to refer to it. I've tried everything, but nothing seems to work.

P.S. The first two classes are always required in my application, and the last registerModel class is called via a controller. Which is why I don't construct the parent in the sub-classes.

Upvotes: 3

Views: 415

Answers (2)

Wing Lian
Wing Lian

Reputation: 2418

In your register model, the constructor needs to call the parent constructor

<?php
class registerModel extends Model {
public function __construct() {
    echo "This is the register Model";
    parent::__construct();
}

And then you can access it from

$this->db

Upvotes: 2

Ry-
Ry-

Reputation: 224963

Make it a field inside the Database class:

class Database extends mysqli {
    public $mysqli;

    public function __construct() {
        parent::__construct();
        $this->mysqli = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBDATABASE);

        if (mysqli_connect_errno()) {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }
    }   
}

Then you can refer to it like so:

$stmt = $this->db->mysqli->prepare("INSERT INTO users (firstName, lastName) values (?, ?)");

But you also need to keep the parent constructor:

echo "This is the register Model";
parent::__construct();

Finally, your Database class shouldn't extend mysqli, because you don't actually use that inheritance; you're creating a completely different object.

Upvotes: 2

Related Questions