php-pdo命名空间在类扩展中出现致命错误


php pdo namespace fatal error in class extend

我创建了返回pdo连接对象的连接类。其他模型类扩展了该类。在视图模式下,我尝试使用命名空间和自动加载类来获取输出,但它出现了一些致命错误"对非对象的成员函数query()的调用"。帮我解决这个问题。

这是Connection.php

namespace myproject;
use PDO;
class Connection
{
    private $host = "localhost";
    private $user = "root";
    private $pass = "";
    private $dbname = "mydb";
    public $dbh;
    private $error;

    public function __construct()
    {
        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
        try{
            $this->dbh = new PDO($dsn, $this->user, $this->pass);
            $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $this->dbh;
        }
        // Catch any errors
        catch(PDOException $e){
            $this->error = $e->getMessage();
        }
    }
} 

然后我将这个类扩展到其他类Form.php

namespace myproject;
use myproject'Connection;
class Form extends Connection
{
    public function GetUser($id)
    {
        $sql = "select * from users where uid='$id'";
        $query = $this->dbh->query($sql);
        $data = $query->fetch(PDO::FETCH_ASSOC);
        $uname = $data[first_name]." ".$data[last_name];
        return $uname;  
    }
}

在前端页面中,出现了我上面指出的错误消息。

namespace myproject;
include 'Form.php';
include 'Connection.php';
$test = new Form();
echo $test->GetUser(1);

您的Form.php文件应该是:-

namespace myproject;
use PDO;  // add this line
class Form extends Connection{
    public function GetUser($id)
    {
        $sql = "select * from users where uid='$id'";
        $query = $this->dbh->query($sql);
        $data = $query->fetch(PDO::FETCH_ASSOC);
        // added single quotes around first_name and last_name
        $uname = $data['first_name']." ".$data['last_name']; // added single quotes around first_name and last_name
        return $uname;  
    }
}

您的视图文件应该是:-

<?php
namespace myproject;
include 'Connection.php'; // include connection file first
include 'Form.php'; // include form file second
$test = new Form();
echo $test->GetUser(1);

希望它能帮助你:-)