I want to scan directories and subdirectories, make list of xml files, take content from xml files and display it. This functions work correctly without OOP. I try to create a class. I call function scandir_through
from function main
. I haven't errors, result too.
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();
?>
The problem is because the $dir
instance variable isn't what you're accessing within your main method. (It's looking for a $dir
variable in the scope of that method, rather than at the class level.)
What you need to use is...
$scan_tree = $this->scandir_through($this->dir);
If you turn on E_NOTICE warnings, you'll see that it'll have been throwing an error.
I think that $dir should be an argument for main. Just think if you had nothing else in the class, where would main get $dir from?
I would change:
public function main()
to
public function main($dir)
and when you call main using $d, include the dir so change that to:
$d->main($dir);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With