Calling ADODB inside a function?
I'm wondering why when i put an sql ADODB query in side a function it produces the following error:
Fatal error: Call to a member function Execute() on a non-object in -path to script-
My function is something like:
$dsn = 'mysql://user:pass@localhost/db';
$db = ADONewConnection($dsn);
function getem($q){开发者_运维知识库
$r=$db->Execute($q);
return $r->RecordCount();
}
echo getem("select * from table");
Any ideas how to fix that?
Variable Scope Issue
You need to import $db
instance into your function using global
keyword:
function getem($q){
global $db;
$r=$db->Execute($q);
return $r->RecordCount();
}
That should do the trick.
More Info:
- http://php.net/manual/en/language.variables.scope.php
variable scope issue
inside the function, the local variables of $db
is not defined
ugly fix is to use global like
function getem($q)
{
global $db;
$r=$db->Execute($q);
return $r->RecordCount();
}
Or you can consider wrap the adodb as static class like
class db
{
protected static $db;
public static function execute($query)
{
if (!self::$db) // or check object instance type
{
self::$db = ADONewConnection('mysql://user:pass@localhost/db');
}
return self::$db->execute($query);
}
}
function getem($q)
{
$r=db::execute($q);
return $r->RecordCount();
}
精彩评论