1

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']";


  }

}

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Your $database variable hasn't been initialised as an array before assigning values to it. Try:

private $database = [];

1 Comment

still error Array to string conversion in this line $this->database['dsn'] = "mysql:host=$this->database['host'];dbname=$this->database['db']";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.