I’m trying to become an object-oriented coder here, so I’m giving myself some simple tasks.
I built a class that displays all the images in a given directory. That worked fine, so I separated that class into two classes, one to read the filenames in the directory and pass them into an array, and one to parse that array and display the pictures. The method in the child class is exactly the same as it was when it was in the parent class (except of course substituting parent:: for this->).
Now it seems when I instantiate the child class and call its method, nothing happens at all.
Classes:
class Picfind
{
public function findPics($dir){
$files = array();
$i=0;
$handle = opendir($dir);
while (false !== ($file = readdir($handle))){
$extension = strtolower(substr(strrchr($file, '.'), 1));
if($extension == 'jpg' || $extension == 'gif' || $extension == 'png'){
// now use $file as you like
$i++;
$files['file' . $i] = $file;
}
}
return $files;
}
}
class DisplayPics extends Picfind
{
function diplayPics($dir)
{
echo 'displayPics method called';
foreach(parent::findPics($dir) as $key => $val) {
echo '<img src="' . $dir . $val . '" img><br/>';
}
}
}
Instantiation:
include("class.picFind.php");
$Myclass = new DisplayPics();
$Myclass->displayPics('./images/');
To be honest: your whole design is wrong.
DisplayPicsshouldn’t inherit fromPicfind. Honestly, either havePicfindhave a display method, or haveDisplayPicstake the output fromPicfind. Think, does the following make sense: "DisplayPics is a PicFind."? If not, it’s probably wrong.Pictures, withfindanddisplaymethods. In your case, you are finding something in a directory, which leads to the next point:DirectoryIteratorclass. This way, you can do whatever you’d like with the files you find. You’ll have all the information about the file available to you, and it’s integrated nicely with PHP.How to use:
Note that you could use the
ExtensionFinderclass I defined above to find files of ANY extension. That could potentially be more useful than simply finding images, but I defined aPictureFinderclass for you for that specific use-case.