简体   繁体   English

在php类构造中使用数组将数组转换为字符串会出错

[英]use array in php class construct get Array to string conversion error

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']"; 这行有什么问题$ 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. 使用简单的语法(不使用大括号),PHP只是试图将$this->database插入字符串中,这在将数组转换为字符串时会发出通知。


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. 在将$database变量赋值之前,尚未将其初始化为数组。 Try: 尝试:

private $database = [];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM