简体   繁体   English

在函数内部调用ADODB?

[英]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: 我想知道为什么当我在函数中放置sql ADODB查询时会产生以下错误:

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: 您需要使用global关键字将$db实例导入到函数中:

function getem($q){
  global $db;

  $r=$db->Execute($q);
  return $r->RecordCount();
}

That should do the trick. 这应该够了吧。

More Info: 更多信息:

variable scope issue 可变范围问题

inside the function, the local variables of $db is not defined 在函数内部,未定义$db的局部变量

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 或者您可以考虑将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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM