【问题标题】:Fatal Error : Call to undefined method Database::query()致命错误:调用未定义的方法 Database::query()
【发布时间】:2013-09-04 13:02:53
【问题描述】:

我在这部分的某处有一个错误(**Fatal Error : Call to undefined method Database::query()**),我不知道这是从哪里来的。因为我只是改变了我的构造函数

Class Database{

public function __construct(){

    $this->getConn();
}
public function getConn(){
    return new mysqli("localhost", "root", "", "os_db");
}
public function select($query){
    $data = array();
    if($result = $this->query($query)){
        while($row = $result->fetch_assoc()){
            $data[] = $row;
        }
    }else{
        $data = array();
    }
return $data;
}
}

如果我将查询更改为if($result = $this->getConn()->query($query).. 它可以完美运行.. 无论如何我必须调用连接我会这样做$this->query($query)

【问题讨论】:

  • 你把你的构造函数改成什么了,之前是什么?
  • $this->query($query) 等同于Database::query($query)
  • 请用您自己的话重复错误信息。另外,告诉我们文件名和行号是什么(它在错误消息中)。您需要了解导致错误的原因。
  • 这个问题是题外话,因为很明显 OP 需要睡觉。
  • $this->query() 在你的类中不存在,简单明了。如果您再次详细查看代码并尝试遵循其不存在的逻辑,那么您应该能够轻松发现许多其他废话。

标签: php class oop mysqli


【解决方案1】:
Class Database {

  public function __construct() {

    $this->getConn(); 

  } 

  public function getConn() { 

    $db = new mysqli("localhost", "root", "", "os_db"); 
    $this->db = $db;

  } 

  public function select($query) { 

    $data = array(); 

    if($result = $this->db->query($query)){ 

      while($row = $result->fetch_assoc()){ 

        $data[] = $row; 

      } 

    } else { 

      $data = array(); 

    } 

    return $data;

  }

}

或者不是每次调用类时都连接,您可以执行以下操作:

Class Database {

  public function __construct() {

  } 

  public function getConn() { 

    $db = new mysqli("localhost", "root", "", "os_db"); 
    $this->db = $db;

  } 

  public function select($query) { 

    $this->getConn();

    $data = array(); 

    if($result = $this->db->query($query)){ 

      while($row = $result->fetch_assoc()){ 

        $data[] = $row; 

      } 

    } else { 

      $data = array(); 

    } 

    return $data;

  }

}

【讨论】:

  • 恐怕你需要更多的 OOP 经验
  • @YourCommonSense 喜欢在哪一部分?
  • 就像“每次调用类”部分一样。
  • 恐怕只有每天使用一项技术才能提高。
  • @YourCommonSense 那么我希望我能随着时间的推移改进:)
猜你喜欢
  • 2013-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-23
  • 2017-05-03
  • 2020-01-04
  • 2018-10-03
相关资源
最近更新 更多