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?
答案 0 :(得分:3)
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).
答案 1 :(得分:2)
the code $config_model->init()
returns object of Config_model class, so you can not 'echo' it, because echo is used for string,
If you wan to test your configuration you may use var_dump()
.
for Ex:
$config_model = new config_model();
var_dump($config_model->init());
答案 2 :(得分:1)
mysqli_report(MYSQLI_REPORT_STRICT);
try {
$connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
} catch (Exception $e ) {
echo "Service unavailable";
echo "message: " . $e->message; // not in live code obviously...
exit;
}
答案 3 :(得分:0)
$ config_model = new config_model();
$ config_model是对象,无法回显它,只需使用var_dump()。