Php 在函数内调用ADODB?
我想知道为什么在函数中放入sql查询时会产生以下错误:Php 在函数内调用ADODB?,php,mysql,Php,Mysql,我想知道为什么在函数中放入sql查询时会产生以下错误: Fatal error: Call to a member function Execute() on a non-object in -path to script- 我的功能类似于: $dsn = 'mysql://user:pass@localhost/db'; $db = ADONewConnection($dsn); function getem($q){ $r=$db->Execute($q); return $r-
Fatal error: Call to a member function Execute() on a non-object in -path to script-
我的功能类似于:
$dsn = 'mysql://user:pass@localhost/db';
$db = ADONewConnection($dsn);
function getem($q){
$r=$db->Execute($q);
return $r->RecordCount();
}
echo getem("select * from table");
有没有办法解决这个问题?可变范围问题 您需要使用
global
关键字将$db
实例导入到函数中:
function getem($q){
global $db;
$r=$db->Execute($q);
return $r->RecordCount();
}
这应该能奏效
更多信息:
global
关键字将$db
实例导入到函数中:
function getem($q){
global $db;
$r=$db->Execute($q);
return $r->RecordCount();
}
这应该能奏效
更多信息:
$db
的局部变量
丑陋的解决方法是使用全局相似的方法
function getem($q)
{
global $db;
$r=$db->Execute($q);
return $r->RecordCount();
}
或您可以考虑将ADODB封装为静态类,如
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();
}
在函数内部,未定义$db
的局部变量
丑陋的解决方法是使用全局相似的方法
function getem($q)
{
global $db;
$r=$db->Execute($q);
return $r->RecordCount();
}
或您可以考虑将ADODB封装为静态类,如
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();
}
不确定为什么它没有为我成功:(@David:实例创建得好吗?
var\u dump($db);
不确定为什么它没有为我成功:(@David:实例创建得好吗?var\u dump($db);