我有一個簡單的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>";
}
}
?>
感謝。
[變量範圍和函數](http://stackoverflow.com/questions/4022536/variable-scope-and-functions),[無法訪問函數內部的全局變量](http:// stackoverflow .com/questions/5449526 /) – outis