PDO无法转换为字符串php

时间:2017-09-26 07:47:40

标签: php mysql pdo

学习PHP OOP方式:

将数据库类对象传递给其他类我收到此消息'可捕获的致命错误:类PDO的对象无法转换为字符串'同时,如果我对此行发表评论并且#39; //$imageobj= new image($dbobj);' ?

更新:在try {}之前,我在db.class.php中将此行$this->dbconn=null;添加到getConnection()函数。一切都很好!!!

  

的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   这个类接收$ dbobject尝试$ dbobject-&gt; getConncetion()并设置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 solve: 捕获致命错误:类PDO的对象无法转换为字符串。 有什么建议吗? enter image description here

1 个答案:

答案 0 :(得分:1)

问题在于:

    new ExtractTextPlugin({
        filename: '[name].bundle.css'
    })

dbname应该是数据库名称。您提供的属性(在添加$ this-&gt; dbconn = null之前)不存在,这就是您收到错误的原因。

添加$ this-&gt; dbconn = null,确实可以防止非existant属性上的致命错误,但您仍然提供空数据库名称。

您应该通过将其替换为$ this-&gt; dbname来修复它,如下所示:

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