【问题标题】:Call to a member function InnerJoin() on a non-object在非对象上调用成员函数 InnerJoin()
【发布时间】:2014-08-07 04:27:55
【问题描述】:

我是 PHP 新手,我正在尝试创建一个具有内部连接功能的数据库类,但出现此错误:

在第 10 行的 C:\xampp\htdocs\world\index.php 中的非对象上调用成员函数 InnerJoin()

我的代码:

<?php 

class DB {
private static $_link = null,
               $_host = "127.0.0.1",
               $_pass = "",
               $_dbname = "mundo",
               $_user = "root",
               $_charset = "utf8";
private $_pdo,
        $_query,
        $_count = 0,
        $_error = false,
        $_results;

private function __construct() {
    $this->_pdo = new PDO("mysql:host=".self::$_host.";dbname=".self::$_dbname,self::$_user,self::$_pass);
}

public static function getLink() {
    if(!isset(self::$_link)) {
        self::$_link = new DB();
    }
    return self::$_link;
}

public function Get($table) {
    return $this->_query = "SELECT * FROM ".$table;
}

public function Go() {
    if($this->_query = $this->_pdo->prepare($sql)) {
        echo "prepared";
    }
}

public function InnerJoin($table1, $column1, $table2, $column2){
    return $this->_query = $this->_query." INNER JOIN ".$table2." ON ".$table1.".".$column1." = ".$table2.".".$column2;
}
}
?>

在我的 index.php 中有这个:

<?php 
$DB = DB::getLink()->Get("paises")->InnerJoin("paises","Id_Continente","Continentes","Id_Continente")->Go();
?>

希望你能帮帮我,谢谢

【问题讨论】:

    标签: php database class


    【解决方案1】:

    因为您从Get 函数返回$this-&gt;_query,因为它需要返回一个完整的对象才能再次使用它,

    public function Get($table) {
        $this->_query = "SELECT * FROM ".$table;
        return $this;
    }
    

    更多详情请阅读Method Chaining

    【讨论】:

    • 他返回的是布尔值,而不是_query
    • 我只需要返回 $this 而不是 $this->_query,我已经用解决方案更新了问题
    • 您无法更新相关答案。如果这个答案对您有帮助,请accept 它,以便对未来的用户有所帮助。
    • 我已经回滚到你原来的问题。现在没什么可更新的。享受编码!
    【解决方案2】:
    $DB = DB::getLink()->Get("paises")->InnerJoin("paises","Id_Continente","Continentes","Id_Continente")->Go()
    

    你在一条指令中有 3 个方法调用......当每个函数返回必须调用下一个函数的对象时,这没有问题。

    但这不是在这里发生的。

    getLink() 初始化对象数据库并返回它,所以接下来就可以了:

    DB->Get("paises")
    

    这会返回一个布尔值,告诉您分配 $this-&gt;_query = "SELECT * FROM ".$table; 是否成功...这是您失败的时间:

    1->InnerJoin
    

    尽量不要一次完成所有工作,检查回报并相应地构建下一步。

    【讨论】:

    • 我只需要返回 $this 而不是 $this->_query,我已经用解决方案更新了问题
    猜你喜欢
    • 2010-09-26
    • 2012-04-20
    • 2015-05-01
    • 2013-12-01
    • 2015-12-23
    • 2015-08-29
    • 2015-02-02
    • 2015-05-22
    • 2015-03-24
    相关资源
    最近更新 更多