我创建了返回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);
答案 0 :(得分: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);
希望它会对你有所帮助: - )