2015-02-07 3 views
0

Я разрабатываю веб-приложение с использованием php. Я создал класс базы данных, к которому я получу доступ. Теперь в новом файле я доступа к этому классу, но я получаю сообщение об ошибке:ошибка при подключении к базе данных

!) Catchable fatal error: Object of class DbMain could not be converted to string in C:\wamp\www\baapdevelopers\DBMain.php on line 23 

код

<?php 
class DbMain{ 
    private $host = 'localhost'; 
    private $dbname = 'test'; 
    private $username = 'root'; 
    private $password = ''; 

    public $con; 

    function __construct(){ 
     $this->connect(); 
    }// this is the main constructor used for initializing the database 

    function connect(){ 
     try{ 
      $this->con = new PDO("mysql:host=$this-host;dbname=$this->dbname",$this->username, $this->password); 
      $this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); 
     }catch(PDOException $e){ 
      echo 'We\'re sorry but there was an error while trying to connect to the database'; 
      file_put_contents('connection.errors.txt', $e->getMessage().PHP_EOL,FILE_APPEND); 
     } 
    } 
} 
/* Test.php */ 

//include_once("DBMain.php"); 
$db = new DbMain(); 
?> 

Я не знаю, почему эта ошибка происходя

+0

Вы пропустили стрелку «->» в строке '$ this-> con = new PDO (" mysql: host = $ this-> host; dbname = $ this-> dbname ", $ this-> username, $ this-> password); ' – SHAZ

ответ

3

В этой строке:

$this->con = new PDO("mysql:host=$this-host;dbname=$this->dbname",$this->username, $this->password); 

Когда вы используете $this->dbname, например, в строке, он видит только $this в качестве va и, таким образом, попытается преобразовать $this (который действительно является экземпляром класса DbMain) в строку. Об этом сообщает сообщение об ошибке.

Вместо этого вам следует избегать сложных имен переменных в строке с фигурными фигурными скобками ({$this->dbname}). Ваш код становится:

$this->con = new PDO("mysql:host={$this->host};dbname={$this->dbname}",$this->username, $this->password); 

Более подробной информации об этой концепции можно найти here.

+0

И, кстати, он забыл' '' в '$ this-host' –

+0

Yep, также, но я полагаю, что это была опечатка. – Keelan

Смежные вопросы