Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 对象中的Mysql查询_Php_Mysql_Oop - Fatal编程技术网

Php 对象中的Mysql查询

Php 对象中的Mysql查询,php,mysql,oop,Php,Mysql,Oop,到目前为止,我已经写了一个月的面向对象风格,现在我想知道使用sql查询的正确方法是什么。例如,我在类中有函数getPlayerData。那么哪种方式更好- 1) 在类外执行mysql过程,并将获取的数组提供给getPlayerData 2) 在课堂上做所有的程序 如果您建议使用第二种情况,那么我是否应该使用启动mysqli实例的全局$variable启动每个函数 对不起,如果我没有使用正确的术语,你可以随时纠正我。谢谢 不给每个类函数一个全局变量,您可以执行以下操作: class Test{

到目前为止,我已经写了一个月的面向对象风格,现在我想知道使用sql查询的正确方法是什么。例如,我在类中有函数getPlayerData。那么哪种方式更好- 1) 在类外执行mysql过程,并将获取的数组提供给getPlayerData 2) 在课堂上做所有的程序

如果您建议使用第二种情况,那么我是否应该使用启动mysqli实例的全局$variable启动每个函数


对不起,如果我没有使用正确的术语,你可以随时纠正我。谢谢

不给每个类函数一个全局变量,您可以执行以下操作:

class Test{

    protected $mysqli = null;

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

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

    public function getSomething(){
        $result = $this->mysqli->query("SELECT something FROM table");
        //do something with result here
        return $result;
    }

}
允许您像这样使用对象:

$test = new Test($mysqli);
$result = $test->getSomething();


您可以执行以下操作,而不是为每个类函数指定一个全局变量:

class Test{

    protected $mysqli = null;

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

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

    public function getSomething(){
        $result = $this->mysqli->query("SELECT something FROM table");
        //do something with result here
        return $result;
    }

}
允许您像这样使用对象:

$test = new Test($mysqli);
$result = $test->getSomething();


补充韦恩·惠蒂的答案。他在这门课上所做的被称为依赖注入,被认为是这个场景中的最佳实践。这让我非常清楚。我明白了,现在我知道了最好的方法。谢谢:)我在公开帖子中看到我的格式很难看,所以对此表示抱歉。补充韦恩·惠蒂的答案。他在这门课上所做的被称为依赖注入,被认为是这个场景中的最佳实践。这让我非常清楚。我明白了,现在我知道了最好的方法。谢谢:)我在公开的帖子里看到我的格式很难看,所以很抱歉。