Get error Notice: Array to string conversion
what's wrong in this line $this->database['dsn'] = "mysql:host=$this->database['host'];dbname=$this->database['db']";
my code
class databaseClass {
// data variables
private $database;
// Construct
public function __construct() {
// database info
$this->database['host'] = 'localhost';
$this->database['db'] = 'dbname';
$this->database['username'] = 'root';
$this->database['password'] = '123';
$this->database['dsn'] = "mysql:host=$this->database['host'];dbname=$this->database['db']";
}
}
You need to use complex syntax (curly braces) for the variable interpolation.
"mysql:host={$this->database['host']};dbname={$this->database['db']}";
See the "Complex (curly) syntax" section in the manual on variable parsing .
Using simple syntax (without the braces) PHP is just trying to insert $this->database
into the string, which gives you that notice when it converts the array to a string.
Not directly related to that problem, but I'd suggest passing the connection info as arguments to the constructor. Hard coding them in the function body is a very inflexible way to do it. Try using a different database connection for testing, for example.
Your $database
variable hasn't been initialised as an array before assigning values to it. Try:
private $database = [];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.