gpt4 book ai didi

php 在 null 上调用成员函数 query()

转载 作者:太空宇宙 更新时间:2023-11-03 10:40:32 28 4
gpt4 key购买 nike

你好我收到这个错误

Call to a member function query() on null

Fatal error: Call to a member function query() on null

Call to member function query() on Null

但似乎都没有解决我的问题

我有数据库类

class DB
{
private $link;

public function __construct()
{
$this->link = new mysqli(HOSTNAME, USERNAME, PASSWORD, DBNAME);
if ($this->link->connect_error)
{
exit('Some of the database login credentials seem to be wrong.' . $this->link->connect_error);
}
}
}

然后我尝试用这个类查询数据库

class UserModel extends DB
{
private $db;

public function __construct()
{
$this->getUser();
}

public function getUser()
{
$query = $this->db->query("SELECT * FROM users");
var_dump($query);
}
}

这些文件在site/app/model/file.php

我在我的 site/index.php 中实例化数据库

最佳答案

这里有几个错误:

  1. 当您在 UserModel 类中定义自己的构造时,父级 __construct(定义了 $link var)不会运行。您可以将 parent::__construct(); 添加到子构造函数。

  2. 在您的父类中,您有 $link 变量,而不是 $db。并且 $linkprivate,因此它在子类中不可用。

固定代码是

class DB
{
protected $link; // protected here

public function __construct()
{
$this->link = new mysqli(HOSTNAME, USERNAME, PASSWORD, DBNAME);
if ($this->link->connect_error)
{
exit('Some of the database login credentials seem to be wrong.' . $this->link->connect_error);
}
}
}


class UserModel extends DB
{

public function __construct()
{
// call parent construct and define $this->link
parent::__construct();
$this->getUser();
}

public function getUser()
{
// use $this->link
$query = $this->link->query("SELECT * FROM users");
var_dump($query);
}
}

关于php 在 null 上调用成员函数 query(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39434570/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com