[英]use array in php class construct get Array to string conversion error
獲取錯誤通知:數組到字符串的轉換
這行有什么問題$ this-> database ['dsn'] =“ mysql:host = $ this-> database ['host']; dbname = $ this-> database ['db']”;
我的密碼
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']";
}
}
您需要對變量插值使用復雜的語法(大括號)。
"mysql:host={$this->database['host']};dbname={$this->database['db']}";
請參閱有關變量解析的手冊中的“復雜(卷曲)語法”部分。
使用簡單的語法(不使用大括號),PHP只是試圖將$this->database
插入字符串中,這在將數組轉換為字符串時會發出通知。
與該問題沒有直接關系,但是我建議將連接信息作為參數傳遞給構造函數。 在功能主體中對其進行硬編碼是一種非常不靈活的方法。 例如,嘗試使用其他數據庫連接進行測試。
在將$database
變量賦值之前,尚未將其初始化為數組。 嘗試:
private $database = [];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.