DISCLAIMER: since question obviously has been already answered, this is a long form comment on provided code.
编写类时,应尽量避免在构造函数中进行计算。这使得难以调试代码。
我实际上会像这样构造代码:
class ImageData {
protected $count = 0;
protected $dir = null;
protected $dirArray = null;
public function __construct( $dir = 'panos/thumbs') {
$this->dir = $dir;
}
public function getCount(){
if ( is_array($this->dirArray) ){
$this->initialize();
}
return $this->count;
}
public function getArray(){
if ( is_array($this->dirArray) ){
$this->initialize();
}
return $this->dirArray;
}
protected function initialize(){
$this->dirArray = $this->findImages();
sort($this->dirArray);
$this->count = count($dirArray);
}
protected function findImages( $extensions = array('jpg') ){
$files = array();
$dirCon = opendir($this->dir);
while ($name = readdir($dirCon)){
$current = strtolower(substr($foo, strrpos($foo, '.')+1));
if ( in_array( $current, $extensions ) ){
$files[] = $name;
}
}
closedir($dirCon);
return $files
}
}首先,我建议使用protected而不是private,如果你现在不需要它们private。因为类的private成员不是“可见的”,所以在扩展类时。
另一件事是将对象的初始化移动到实际需要的位置。通过微小的修改,这个类可以让你重复搜索文件夹,甚至可以在不同的文件夹中搜索。
如果您想学习如何在PHP的上下文中使用OOP,请首先阅读http://php.net/manual/en/language.oop5.php。你可能会发现PHP Object-Oriented Solutions书是一个很大的帮助。