PDO不能转换成字符串PHP

PDO不能转换成字符串PHP

问题描述:

学习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

问题就出在这里:

"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