Passing mysqli to class for function use

南楼画角 提交于 2020-01-02 19:46:55

问题


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();


来源:https://stackoverflow.com/questions/14803727/passing-mysqli-to-class-for-function-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!