2011-12-02 55 views
-1

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

代码递归地从数据库FYI中打印嵌套注释。

的代码如下...

<?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>"; 
    } 
} 
?> 

感谢。

+0

[变量范围和函数](http://stackoverflow.com/questions/4022536/variable-scope-and-functions),[无法访问函数内部的全局变量](http:// stackoverflow .com/questions/5449526 /) – outis

回答

1

你需要通过你的$ DB连接功能,像这样:

function recursive_categories($results, $db) 

那么这将是可用的功能变量范围内。

想到另一个问题......如果这个文件驻留在一个可公开访问的Web目录中,那么你肯定不希望让你的实际数据库凭据在公开的环境中冷却。

+0

谢谢,就是这样,非常感谢。顺便说一下新手Q的道歉。这只是为了测试数据库凭证。 –