Passing mysqli to class for function use

2019-05-28 02:30发布

问题:

Probably asked many times but I am hard-headed.

I have the following class to manage a MySQL db.

class blog {        
    function show ($mysqli) {
    // Code working on $mysqli here
    }
}

Since I will be using $mysqli in many functions inside of this class I read that I can create constructors in order to pass the $mysqli variable to the class and use it inside of each function so I can do something like:

$blog = new blog($mysqli);
$blog -> show();

Is this possible?

回答1:

This is called Dependency injection.

Just use a field $mysqli in your class and initialize it in your constructor and use it via $this->mysqli:

class blog {  
    private $mysqli;

    function __construct(mysqli $mysqli) {
        $this->mysqli = $mysqli;
    }

    function show () {
        // Code working on $this->mysqli here
    }
}


回答2:

To store it in the class, would be something like:

class blog {
    private $mysqli;
    function __construct($dbi) {
        $this->mysqli = $dbi;
    }        
    function show () {
    $this->mysqli->query(); //example usage
    // Code working on $mysqli here
    }
}

And then in your code to use the class:

$blog = new blog($mysqli);
$blog->show();