This is a question on style and use of functions (I am trying to improve my coding). One of the most common recurring patterns in my code is along the lines:
conditional 1 >> loop >> conditional 2 etc etc
DO THIS
else
DO SOMETHING ELSE
end conditionals and loops.
I am looking for ways to construct this that allow me to apply different "DO THIS" options to the overall pattern. Here's an example that scans a directory tree and prints the contents to the browser. The fact that it is recursive is irrelevant, as is the messy ordering of the output, what I am interested in is the approach to setting the "DO THIS" options:
<?php
$thisdir = 'test';
function scandir($dir, $diraction, $fileaction) {
$handle = opendir($dir);
while (false!==($FolderOrFile = readdir($handle))) {
if($FolderOrFile != "." && $FolderOrFile != "..") {
if(is_dir("$dir/$FolderOrFile")) {
$diraction ("$FolderOrFile"); // <DO THIS
scandir("$dir/$FolderOrFile", $diraction, $fileaction);
}
else {
$fileaction ("$FolderOrFile"); // <DO THAT
}
}
}
closedir($handle);
}
function dirreport ($FolderOrFile) {
print "<p>Folder: $FolderOrFile</p>\n";
}
function filereport ($FolderOrFile) {
print "<p>File: $FolderOrFile</p>\n";
}
scandir("$thisdir", "dirreport", "filereport");
?>
It can alternatively be structured
<?php
$thisdir = 'test';
function scandir($dir, $diraction, $fileaction) {
$handle = opendir($dir);
while (false!==($FolderOrFile = readdir($handle))) {
if($FolderOrFile != "." && $FolderOrFile != "..") {
if(is_dir("$dir/$FolderOrFile")) {
eval ($diraction); // <DO THIS
scandir("$dir/$FolderOrFile", $diraction, $fileaction);
}
else {
eval ($fileaction); // <DO THAT
}
}
}
closedir($handle);
}
function scandir_report ($targetdir) {
$thisdiraction = 'print "<p>Folder: $FolderOrFile</p>";';
$thisfileaction = 'print "<p>File: $FolderOrFile</p>";';
scandir($targetdir, $thisdiraction, $thisfileaction);
}
scandir_report("$thisdir");
?>
I find the second clearer but is either of these preferred, is something else much better, is this a sensible approach? I hope this isn't too vague a question, I spent plenty of time getting to those examples and they both work fine. I would appreciate any feedback from the experienced coders.
Andrew