好的,2个单独的php文件,一个是主脚本,另一个是类。我正在尝试使用 PDO 连接到 sql 数据库。我在主脚本中创建 PDO 连接,然后将其传递给另一个脚本中的类,在该类中进行查询。但是,我收到以下错误:
Fatal error: Call to a member function prepare() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/test/class.php on line 16
我的理解是 PHP 可以跨脚本传递对对象的引用,但错误表明该对象不存在。
下面是主要的 php 脚本,创建 PDO 对象并传递给要使用的类。
<?php
session_start();
unset($_SESSION['reference']);
require('class.php');
//connect to database, I know that username and password are not included
$dsn = 'mysql:dbname=test;host=localhost';
try {
$dbh = new PDO($dsn);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die ( 'Connection failed: ' . $e->getMessage() );
}
$objReference = new reference($dbh);
$reference = $objReference->getReference();
$_SESSION['reference'] = $reference;
session_write_close();
?>
下面是 class.php 文件。接收对象并获取数据。
<?php
class reference
{
private $reference;
private $dbh;
public function __construct($dbh) {
$this->dbh=$dbh;
$this->setReference();
}
private function setReference() {
$refid=$dbh->prepare(" SELECT MAX(id) FROM createX ");
$refid->execute();
$id = $refid->fetchColumn();
$id=$id+1;
$this->reference = $id;
}
public function getReference() {
return $this->reference;
}
}
?>
是否有另一种方法可以将 PDO 对象传递给我不知道的类?谢谢大家。