MySQLI在类和函数中

时间:2013-11-26 12:20:41

标签: php function class syntax mysqli

我的问题很简单,在这里检查了几个点后,我觉得最好问一个新问题。

假设我有2个班级

class FirstClass {

  function test() {
    return "info";
  }

}

class SecondClass {

  function test() {
    return "info";
  }

}

然后我有我的mysqli对象

$mysqli = new mysqli(host, user, password, db);

我需要做些什么才能在类中的函数内使用mysqli对象。

到目前为止,这是我的2个想法,尽管我还没有把它放在网站上进行测试。

class FirstClass {
global $mysqli;

  function test() {
    $mysqli->query("some query");
    return "info";
  }

}

class FirstClass {

  function test() {
    global $mysqli;
    $mysqli->query("some query");
    return "info";
  }

}

我很确定如果需要我可以设置构造但是我只需要知道哪种方式是分享mysqli对象的最佳方式/唯一方式。

由于


编辑:

所以我做了很多学习,现在有更多的经验来传递信息。

这是我使用的最新工作示例类型。

namespace Page;
use mysqli;

class edit extends details{
  protected $db;

  //this function is actually in the details class but there is no point in demoing 2 classes
  function __construct(mysqli $con){
    $this->db = $con;
  }
}

2 个答案:

答案 0 :(得分:2)

扩展跪在评论中告诉你的内容并反驳其他答案

class foo {

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

  function test() {
    return $this->mysqli->query("some query");
  }

}

是必须的。
你应该在类之外的某个地方创建一个mysqli实例,然后在coustructor中传递它。

答案 1 :(得分:0)

您可以使用__construct()初始化您的MYSQLi。然后,您可以使用$this在您的课程中访问它。

class FirstClass {

  public function __construct(){
    $this->mysqli = new mysqli("host", "user", "password", "db");
  }

  function test() {
    $this->mysqli->query("some query");
    return "info";
  }

}

如果你想在第二堂课中使用它,你可以用相同的方式构建它或扩展你的第一堂课。

class SecondClass extends FirstClass {

  public function __construct(){
    parent::__construct();
  }

  function test() {
    return "info";
  }

}
相关问题