开发者

"Call to undefined method" when trying to pass handle as a constructor argument

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

开发者_StackOverflow中文版

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.


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 :

http://ca2.php.net/manual/fr/mysqli.get-host-info.php


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

echo $this->db->host_info;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜