2017-09-26 55 views
-2

學習PHP OOP方式:PDO不能轉換成字符串PHP

通數據庫類對象的其他類我得到這個消息「開捕致命錯誤:類PDO的對象無法被轉換成字符串」,同時,代碼工作正常,如果我評論此行'//$imageobj= new image($dbobj);'?

更新:一旦我加入這行$this->dbconn=null;getConnection()功能db.class.php嘗試之前{}。每件事情都很好!

index.php

<?php 
include "./classes/db.class.php"; 
include "./classes/image.class.php"; 

$dbobj= new db(); 
$imageobj= new image($dbobj); 

$page_title="Shopping Center !"; 
include './template/header.php'; 

$dbobj->getConnection(); 

include './template/footer.php'; 

db.class.php

class db { 
    private $host; 
    private $dbname; 
    private $username; 
    private $password; 
    private $dbconn; 
    private $status; 

    public function __construct() { 
     // the require paramaters to start db connnection 
     $this->host = '127.0.0.1'; 
     $this->dbname = 'shop_carta'; 
     $this->username = 'root'; 
     $this->password = ''; 
     $this->status = 0; 
     //$this->dbconn = null; 
    } 

    public function getConnection() { 
     try { 
      $this->dbconn = new PDO("mysql:host=$this->host;dbname=$this->dbconn", $this->username, $this->password); 
      if (!is_null($this->dbconn)) { 

       $this->status = $this->dbconn->getAttribute(PDO::ATTR_CONNECTION_STATUS); 
       $this->dbconn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 
       $this->dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

       return $this->dbconn; 
      } else { 
       echo "<div class='alert alert-danger'>" 
       . " Our server Busy Now try again later.. </div></br>"; 
       return false; 
      } 
     } catch (PDOException $ex) { 
       return false; 
     }}} 

image.class.php this class receive the $dbobject try to $dbobject->getConncetion() and set retrieve

class image { 
    private $table_name = 'product_images'; 
    private $dbconn; 
    public $id; 
    public $name; 

    public function __construct($dbobj) { 
     $this->dbconn = $dbobj->getConnection(); 
     }}     

Error message once you pass $dbobj to image class

once you commit line $imageobj= new image($dbobj); in index.php

將dbconn指定爲null解決方案: 可捕獲的致命錯誤:類PDO的對象無法轉換爲字符串。 任何建議爲什麼? enter image description here

+1

顯示圖像類的代碼 - 似乎image'的'的構造函數只接受字符串,但你傳遞整個'db'對象 –

+0

class image {0}私人$ table_name ='product_images'; private $ dbconn; public $ id; public $ name;公共函數__construct($ dbobj){ $ this-> dbconn = $ dbobj-> getConnection(); }} – Mvrk

回答

1

問題就出在這裏:

"mysql:host=$this->host;dbname=$this->dbconn" 

DBNAME應該是一個數據庫名稱。您提供的屬性(在添加$ this-> dbconn = null之前)不存在,這就是您遇到錯誤的原因。

添加$ this-> dbconn = null,可以防止致命的不存在的屬性,但你仍然提供一個空的數據庫名稱。

你應該用這個 - $> DBNAME取代它,像這樣解決這個問題:

"mysql:host=$this->host;dbname=$this->dbname" 
+0

這是愚蠢的錯誤感覺很愚蠢:/。謝謝@Erik。 – Mvrk