我是一个没有经验的 php 程序员,几天前才发现 PDO。我现在正在尝试将我的网站代码移植到使用 PDO,但是当我尝试使用我创建的 PDO 对象时出现错误。
我得到的错误是:
Fatal error: Call to a member function prepare() on a non-object in ... file2.php ...
代码如下所示:
索引.php
class myClass
{
... variables ...
... functions ...
public function myFunction() // gets called on page load, outputs content to page
{
... stuff ...
require('file1.php');
... stuff ...
}
}
文件1.php
require_once('mysql_connect.php'); // create pdo object if not created
... stuff ...
require_once('file2.php');
// I can use the PDO object in here to make queries
$output = function2(); // function2 is in file2.php
... stuff ...
文件2.php
require_once('mysql_connect.php'); // create pdo object if not created
function function2()
{
... stuff ...
// PDO error occurs here
$stmt = $db->prepare(...);
makeQuery($stmt, array(...));
return $something;
}
mysql_connect.php
try
{
$db = new PDO("mysql:$dbhost=localhost;dbname=$dbname;charset=utf8", $dbuser, $dbpass, array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch (PDOException $e)
{
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
function makeQuery($stmt, $array = array())
{
try
{
$stmt->execute($array);
}
catch (PDOException $e)
{
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}