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'));
Your mistake is in your method, your method calls itself recursively via:
getDirContents();
but should do so like (in your Dira class):
$this->getDirContents();
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);