【问题标题】:PHP Uncaught Error: Call to a member function query() on null,PHP 未捕获错误:在 null 上调用成员函数 query(),
【发布时间】:2017-12-06 10:27:39
【问题描述】:

我正在研究 php 并试图自己将它与 oop 集成,谁能解释这个错误的想法?

我猜它找不到查询,但我不明白为什么,因为在 $query 中一切都是正确的,p.s global $mysqli 仅用于测试目的,我知道不小心使用它是不好的。

    <?php 

class Index{
    public function connect(){
    $mysqli=new mysqli();
    $mysqli->connect('localhost',"root","");
    $conn=$mysqli->select_db("webartisan");

    if($mysqli->errno){
    echo "Unable to connect to the database: ".$mysqli->error;
    exit();
    }
 }
public function select_data($table,$id){
    $query="SELECT * FROM {$table} WHERE id=$id  ";
    }
    public function insert_data(){
        global $conn;
        $username=$_POST['username'];
        $password=$_POST['password'];
        $query="INSERT INTO artisan(username,password) VALUES('$username','$password')";

        $result=$conn->query($query);

        if($result->num_rows){
            return true;
        }
    }
    public function register(){
        if(isset($_POST['submit'])){
            self::insert_data();
        }
    }   
}
$index=new Index();
$index->register();
?>

<form method="POST" action="index.php">
    <input type="text" name="username"><br><br>
    <input type="password" name="password"><br><br>
    <input type="submit" name="submit">

</form>

错误:

致命错误:未捕获的错误:在 null 上调用成员函数 query() 在 C:\xampp\htdocs\webartisan\index.php:23 堆栈跟踪:#0 C:\xampp\htdocs\webartisan\index.php(31): 索引->insert_data() #1 C:\xampp\htdocs\webartisan\index.php(36): Index->​​register() #2 {main} 在第 23 行的 C:\xampp\htdocs\webartisan\index.php 中抛出

【问题讨论】:

  • 如果你想在一个类的方法之间共享变量,那么$conn应该是$this-&gt;conn,这意味着你可以去掉global $conn
  • 但是 $conn 在函数内部,所以我应该找到其他方法吗?
  • 您的函数被包装在类中,它们的行为与您所期望的略有不同。将self::insert_data(); 更改为$this-&gt;insert_data();,因为不需要静态调用。我不确定你在哪里打电话给connect()。
  • 我应该找到其他方法吗? @Scuzzy 给了你正确的方向...摆脱global 任何你可以...代码OOP跨度>
  • 现在 $conn 未定义,我调用了 connect() 但仍然未定义

标签: php


【解决方案1】:

$conn 变量不能作为全局变量访问,因为您在 connect() 方法中将 $conn 声明为局部变量。

要解决这个问题,您需要声明为类字段,然后您可以在类Index 的任何方法中以$this-&gt;conn 访问$conn。这样你就不需要global $conn。

例如:

<?php
class Index{
    private $conn;

    public function connect() {
        ...
        $this->conn = $mysqli->select_db("webartisan");
        ...
    }

    public function insert_data() {
        ...
        $result = $this->conn->query($query);
        ...
    }    
}

更新:

select_db() 返回布尔值,而不是连接对象。正如您在评论中所说,以下行将导致Call to a member function query() on boolean 错误。

$this->conn = $mysqli->select_db("webartisan");

您应该阅读mysqli documentation。

【讨论】:

  • 现在它说在布尔值上调用成员函数 query(),这意味着它由于某种原因返回 false 对吗?
  • 正确,表示你的连接失败了。
  • @DummyTarget 这是不同的问题。
  • 你能告诉我什么问题吗?
  • 我确实返回了 $mysqli 并且它有效,但它是正确的做法吗?
猜你喜欢
  • 1970-01-01
  • 2017-07-13
  • 2017-07-31
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
  • 2021-05-21
相关资源
最近更新 更多