“调用未定义的方法”当尝试将句柄作为构造函数参数传递时

发布于 2024-09-16 16:56:45 字数 863 浏览 6 评论 0原文

我有一个需要使用数据库的用户类。为此,我将数据库句柄作为构造函数参数传递,如下所示:

index.php:

<?php

include('classes/user.class.php');

$db = new mysqli('localhost', 'root', '', 'testdb');
if ($mysqli->connect_error)
{
    die('Database connection failed (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}

$user = new User($db);

$db->close();

?>

user.class.php:

<?php

class User
{
    private $db;

    function __construct($db)
    {
        $this->db = $db;
        echo $this->db->host_info();
    }
}

?>

但我收到此错误:

致命错误:调用未定义的方法 mysqli::host_info() 中 C:\xampp\htdocs\classes\user.class.php 第 10 行

我不确定出了什么问题,也许我错误地将数据库句柄传递给了它,但我想不出任何其他方法来做到这一点。即使我在用户类中将 $db 变量设置为 public,我也会收到此错误。

有人可以帮忙吗?谢谢。

I have a user class that I need to use my database with. To do this, I am passing the database handle as a constructor argument like so:

index.php:

<?php

include('classes/user.class.php');

$db = new mysqli('localhost', 'root', '', 'testdb');
if ($mysqli->connect_error)
{
    die('Database connection failed (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}

$user = new User($db);

$db->close();

?>

user.class.php:

<?php

class User
{
    private $db;

    function __construct($db)
    {
        $this->db = $db;
        echo $this->db->host_info();
    }
}

?>

But I get this error:

Fatal error: Call to undefined method
mysqli::host_info() in
C:\xampp\htdocs\classes\user.class.php
on line 10

I'm not sure what's wrong, perhaps I'm incorrectly passing it the handle to the database but I can't think of any other way to do it. Even if I set the $db variable to public in my user class I get this error.

Can anyone help? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吻泪 2024-09-23 16:56:45

host_info 不是方法,而是对象的属性。

您应该使用:

echo $this->db->host_info;

有关更多信息,您可以参考官方文档:

https://www.php.net/manual/fr/mysqli.get-host-info.php

host_info isn't a method, it's a property of the object.

You should use :

echo $this->db->host_info;

For more information you can refer to the official documentation :

https://www.php.net/manual/fr/mysqli.get-host-info.php

笨笨の傻瓜 2024-09-23 16:56:45

在这种情况下,host_info 不是方法。它是一种财产。尝试:

echo $this->db->host_info;

host_info is not a method in this case. it is a property. try:

echo $this->db->host_info;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文