-1
class Database {
        private $host = "localwhost"; // intended typo
        private $user = "root";
        private $password = "";
        private $name = "filmy";
        private $connection;
        
        function connect() {
            $this->connection = @ new mysqli($this->host, $this->user, $this->password, $this->name);
            if($this->connection->connect_errno) {
                var_dump($this->connection->connect_errno);
                exit("<h1>Database connection error: $this->connection->connect_errno</h1>");
            }
        }
    }
    
    $database = new Database();
    $database->connect();

When I try to call $database->connect(); I got this fatal error:

Fatal error: Uncaught Error: Object of class mysqli could not be converted to string in C:\xampp\htdocs\database.php:13 Stack trace: #0 C:\xampp\htdocs\database.php(23): Database->connect() #1 {main} thrown in C:\xampp\htdocs\database.php on line 13

The var_dump says $this->connection->connect_errno is int(2002), not a mysqli object.

Dharman
  • 30,962
  • 25
  • 85
  • 135
luksio
  • 1
  • 1
  • You need to stop manually checking for errors. Please read: [Should we ever check for mysqli_connect() errors manually?](https://stackoverflow.com/q/58808332/1839439) and [Should I manually check for errors when calling “mysqli_stmt_prepare”?](https://stackoverflow.com/q/62216426/1839439) – Dharman Nov 13 '21 at 13:10

1 Answers1

2

You need to use the complex form of variable interpolation to perform double indirection of an object.

exit("<h1>Database connection error: {$this->connection->connect_errno}</h1>");
Barmar
  • 741,623
  • 53
  • 500
  • 612