views:

24

answers:

2

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.

+3  A: 

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

HoLyVieR
Sigh. Should have spotted that. Thanks.
Will
A: 

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

echo $this->db->host_info;
hugo_leonardo