【问题标题】:php scope: class object cant be seen in functionphp范围:在函数中看不到类对象
【发布时间】:2012-01-11 16:22:04
【问题描述】:

我有一个简单的 mysqli 包装类,用于我的数据库操作。我在代码顶部定义(实例化?)该类大概应该是全局可访问的,但是当我尝试在递归函数中使用对 db 类的引用时,xdebug 告诉我它超出了范围 - 所以作为修复,我不得不两次定义数据库,但这似乎是不好的做法。谁能告诉我发生了什么或我哪里出错了?

代码从数据库中递归打印嵌套的 cmets,仅供参考。

代码如下...

<?php
require 'lib/mysqli.class.php';  // the pretty standard mysqli class
$config = array();$config['host'] = 'localhost';$config['user'] = 'root';$config['pass'] = '';$config['table'] = 'publicate';

$db = new DB($config);     // new instance of database
//$db->setFetchMode(2);      // fetch data by association (MYSQLI_ASSOC)

// Run a Query:
$db->query('SELECT * FROM comments WHERE parentid = 0');        

// Get the data:
$root_sql = $db->get();

recursive_categories($root_sql);

function recursive_categories($results)
{
     if(count($results))
     {
         echo "<ul>";
         foreach($results as $res)
         {
             echo "<li>" . "id=" . $res['id'] . ", pid=" . $res['parentid'] . ", content: " . $res['content'];


             //Rest of what ever you want to do with each row

             //Check this category for children ************************
             //2nd definition of DB ************************
             $config = array();$config['host'] = 'localhost';$config['user'] = 'root';$config['pass'] = '';$config['table'] = 'publicate';
             $db2 = new DB($config);     // new instance of database
             $db2->query("SELECT * FROM comments WHERE parentid  = " . $res['id']);
             $rows = $db2->get();

             recursive_categories($rows);

             //has to be after the inner loops
             echo "</li>";
         }
         echo "</ul>";
     }
}
?>

谢谢。

【问题讨论】:

标签: php oop recursion


【解决方案1】:

您需要像这样将 $db 连接传递给函数:

function recursive_categories($results, $db)

然后它将在函数变量范围内可用。

想到的另一个问题...如果此文件位于可公开访问的 Web 目录中,您绝对不希望您的实际数据库凭据只是在开放中冷却。

【讨论】:

  • 谢谢,就是这样,非常感谢。顺便也为新手Q道歉。这只是为了测试数据库凭据。
猜你喜欢
  • 1970-01-01
  • 2013-04-26
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多