problem calling a php method from within itself
class styleFinder{
function styleFinder(){
}
function getFilesNFolders($folder){
$this->folder = $folder ;
if($this->folder==""){
$this->folder = '.';
}
if ($handle = opendir($this->folder)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file<br /> ";
if(is_dir($file)){
echo "<b>" . $file . " is a folder</b><br /> with contents ";
$this::getFilesNFolders($file);
# echo "Found folder";
}
}
}
开发者_运维百科 closedir($handle);
}
}
} I wan to print out a complete tree of folders and files, the script is going into the first folders and finding the files, then finding any sub folders, but not subfolders of those (and yes there is some). Any ideas please?
$this::getFilesNFolders($file);
Should Be
$this->getFilesNFolders($file);
Since PHP 5.1.2 you have this usefull class available: http://www.php.net/manual/en/class.recursivedirectoryiterator.php
Accessing a class function is done like this:
$this->functionName():
Since no one provided that yet, here is the RecursiveDirectoryIterator
version of your code:
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/path/to/directory'),
RecursiveIteratorIterator::SELF_FIRST);
foreach($iterator as $fileObject) {
if($fileObject->isDir()) {
echo "<strong>$fileObject is a folder:</strong><br>\n";
} else {
echo $fileObject, "<br>\n";
}
}
As others have said, within the method itself, you need to call getFilesNFolders with $this -> getFilesNFolders($file)
. Also, the way the code is posted you're missing a } at the end, but since there is one starting the text after the code, that is probably a typo. The code below worked for me (I ran via the command line, so added code to indent different directory levels and also to output \n's):
<?php
class StyleFinder{
function StyleFinder(){
}
function getFilesNFolders($folder, $spaces){
$this->folder = $folder ;
if($this->folder==""){
$this->folder = '.';
}
if ($handle = opendir($this->folder)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($file)){
echo $spaces . "<b>" . $file . " is a folder</b><br/> with contents:\n";
$this -> getFilesNFolders($file, $spaces . " ");
} else {
echo $spaces . "$file<br />\n";
}
}
}
closedir($handle);
}
}
}
$sf = new StyleFinder();
$sf -> getFilesNFolders(".", "");
?>
精彩评论