我是一个没有经验的php程序员,几天前才发现PDO。我现在试图将我的网站代码移植到使用PDO,但是当我尝试使用我创建的PDO对象时出现错误。尝试使用PDO对象时出错
我得到的错误是:
Fatal error: Call to a member function prepare() on a non-object in ... file2.php ...
的代码看起来是这样的:
的index.php
class myClass
{
... variables ...
... functions ...
public function myFunction() // gets called on page load, outputs content to page
{
... stuff ...
require('file1.php');
... stuff ...
}
}
file1.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 ...
file2.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();
}
}
我们需要看代码,但是我敢打赌,如果PDO对象是在'method myfunction()'内部定义的,那么你正在使用的函数中的PDO对象超出了范围。 – 2012-07-05 15:11:18
您应该将错误还有一些关联代码和连接细节已经被清除了。 – 2012-07-05 15:11:23
你能告诉我们代码,而不是描述它吗? – 2012-07-05 15:11:39