Passing mysqli to class for function use

2019-05-28 02:15发布

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?

2条回答
霸刀☆藐视天下
2楼-- · 2019-05-28 02:33

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();
查看更多
别忘想泡老子
3楼-- · 2019-05-28 02:40

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
    }
}
查看更多
登录 后发表回答