0

I have a php code which performs directory/file listing. However, it does not work when called by object.

Following Code Works :

function getDirContents($dir, &$results = array()){
$files = scandir($dir);

foreach($files as $key => $value){
    $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
    if(!is_dir($path)) {
        $results[] = $path;
    } else if($value != "." && $value != "..") {
        getDirContents($path, $results);
        $results[] = $path;
    }
}
// print_r($results);
return $results;
}

var_dump(getDirContents('C:\xampp\htdocs\skillup\d4a1'));

The following code DOES NOT work :

class Dira {
function getDirContents($dir, &$results = array()){
$files = scandir($dir);

foreach($files as $key => $value){
    $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
    if(!is_dir($path)) {
        $results[] = $path;
    } else if($value != "." && $value != "..") {
        getDirContents($path, $results);
        $results[] = $path;
    }
}
// print_r($results);
return $results;
}

}

$obj = new Dira;
$arr = array();
var_dump($obj->getDirContents('C:\xampp\htdocs\skillup\d4a1'));
3
  • Is that your whole code ? Commented Aug 3, 2017 at 10:35
  • 1
    Because you don't know what is $this? Commented Aug 3, 2017 at 10:37
  • yes, but apparently it works with object only if there are no sub-directories inside the given path of the directory Commented Aug 3, 2017 at 10:40

2 Answers 2

2

Your mistake is in your method, your method calls itself recursively via:

getDirContents();

but should do so like (in your Dira class):

$this->getDirContents();
Sign up to request clarification or add additional context in comments.

Comments

1

You are using recursive function getDirContents() but when you call it again you are missing $this .

Try Below Example :

class abc{
    public function getDirContents($dir, &$results = array()){ 
    $files = scandir($dir);

        foreach($files as $key => $value){
            $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
            if(!is_dir($path)) {
                $results[] = $path;
            } else if($value != "." && $value != "..") {
                $this->getDirContents($path, $results);
                $results[] = $path;
            }
        }
    return $results;
    }
}
$res = new abc();
$re = $res->getDirContents('YOUR PATH');
echo '<pre>'; print_r($re);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.