Dram Dram - 10 months ago 47
PHP Question

Mysqli connection issue fatal error

I have the below code:

class config_model
public $host;
public $root;
public $root_password;
public $db;

public function __construct() {
$this->host = "localhost";
$this->root = "root";
$this->root_password = "";
$this->db = "Data";

public function init() {
$mysqli = new mysqli($this->host, $this->root, $this->root_password, $this->db);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
return $mysqli;

$config_model = new config_model();
echo $config_model->init();

When I check the script I see this error:

"Catchable fatal error: Object of class mysqli could not be converted to string".

The erorr is here: "echo $config_model->init();"

How do I handle this error?


Your error is this:

"Catchable fatal error: Object of class mysqli could not be converted to string".

now, read the error: it says Object of class mysqli not be converted to string. Actually read it. Now, I hope you know what an object is, and I also hope you know what a string is. So the Object is somewhere being converted to a string and the object can't handle that conversion.

Where is this happening? Reading your code line by line and you even give the line the error occurs on:

echo $config_model->init();

you are echoing out an object because that is what is being returned by the ->init() method call, init is giving you back an object type. You are then immediately telling PHP to output this object as a string type. This is causing the issue.


PHP has a __ToString() magic method which you can add to your object so that what you call it as a string (which you shouldn't, but...) that the object will run this magic method and output something of your designation.

A simpler solution is also not to try and output objects as strings, instead using routines such as print_r or var_dump if you really need to (but as stated, you shouldn't be doing this at all in a perfect world).