“调用未定义的方法”当尝试将句柄作为构造函数参数传递时
我有一个需要使用数据库的用户类。为此,我将数据库句柄作为构造函数参数传递,如下所示:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
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 :
For more information you can refer to the official documentation :
https://www.php.net/manual/fr/mysqli.get-host-info.php
在这种情况下,host_info 不是方法。它是一种财产。尝试:
host_info is not a method in this case. it is a property. try: