Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call one function from another function in PHP class

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. " &nbsp   ";
                   //echo $title. " &nbsp   ";
                   //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();
?>
like image 897
vili Avatar asked Aug 08 '13 17:08

vili


2 Answers

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.

like image 97
John Parker Avatar answered Sep 28 '22 01:09

John Parker


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);
like image 36
user1522901 Avatar answered Sep 28 '22 01:09

user1522901