[英]Call one function from another function in PHP class
我想掃描目錄和子目錄,制作xml文件列表,從xml文件中獲取內容並顯示它。 此功能無需OOP即可正常工作。 我嘗試創建一個類。 我從函數main
調用函數scandir_through
。 我沒有錯誤,結果也是如此。
class data {
var $dir = 'D:\wamp4\www\begin';
public function scandir_through($dir)
{
$items = glob($dir . '/*');
for ($i = 0; $i < count($items); $i++) {
if (is_dir($items[$i])) {
$add = glob($items[$i] . '/*');
$items = array_merge($items, $add);
}
}
return $items;
}
public function main()
{
$scan_tree = $this->scandir_through($dir);
echo "<ul id='booklist'>"."</n>";
foreach ($scan_tree as $key=>$file){
$url = $file;
$xml = simplexml_load_file($url);
$book_count = count($xml->book);
for($i = 0; $i < $book_count; $i++) {
$book = $xml->book[$i];
$title=$xml->book[$i]->title;
$author=$xml->book[$i]->author;
//echo '</br>';
//echo $file. "   ";
//echo $title. "   ";
//echo $author;
echo "<li><div class='file'>".$file."</div>
<div class='title'>".$title."</div>
<div class='author'>".$author."</div></li></n>";
}
}
echo "</ul>";
}
}
$d = new data();
$d->main();
?>
問題是因為$dir
實例變量不是您在main方法中訪問的內容。 (它在該方法的范圍內尋找$dir
變量,而不是在類級別。)
你需要使用的是......
$scan_tree = $this->scandir_through($this->dir);
如果你打開E_NOTICE警告,你會發現它會拋出錯誤。
我認為$ dir應該是主要的論據。 試想一下,如果你在課堂上沒有別的東西,主要從哪里得到$ dir?
我會改變:
public function main()
至
public function main($dir)
當你使用$ d調用main時,請包含dir,然后將其更改為:
$d->main($dir);
$items=data::scandir_through($dir);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.