學習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();
}}
將dbconn指定爲null解決方案: 可捕獲的致命錯誤:類PDO的對象無法轉換爲字符串。 任何建議爲什麼?
顯示圖像類的代碼 - 似乎image'的'的構造函數只接受字符串,但你傳遞整個'db'對象 –
class image {0}私人$ table_name ='product_images'; private $ dbconn; public $ id; public $ name;公共函數__construct($ dbobj){ $ this-> dbconn = $ dbobj-> getConnection(); }} – Mvrk