$list_of_files
指的是一个变量,它与一个属性不同$this->list_of_files
。
在函数中声明/引用的变量仅在该函数中可用(除非您使用全局 - 但这通常被认为是“邪恶的”,应该避免)
属性可从类中的所有方法获得(除非它们是静态的),并且在对象的生命周期内持续存在。
<?php
//lets show all error so we can see if anything else is going on..
error_reporting(E_ALL & ~E_NOTICE);
class listOfFiles {
private $list_of_files = [];
function __construct() {
if ($handle = opendir(WEB_STORAGE_DIR)) {
while (false !== ($entry = readdir($handle))) {
$this->list_of_files[$entry] = filesize(WEB_STORAGE_DIR.DIRECTORY_SEPARATOR.$entry);
}
closedir($handle);
// Remove . and .. from the list
unset($this->list_of_files['.']);
unset($this->list_of_files['..']);
}
}
function is_empty() {
return empty($this->list_of_files);
}
}
是目录不存在的问题吗?最好在尝试打开之前检查它,并允许在它确实存在但您实际上无法阅读它时执行什么操作:
<?php
//lets show all error so we can see if anything else is going on..
error_reporting(E_ALL & ~E_NOTICE);
class listOfFiles {
private $list_of_files = [];
function __construct() {
if(!is_dir(WEB_STORAGE_DIR)){
throw new Exception("Missing Web Storage Directory");
}
$handle = opendir(WEB_STORAGE_DIR);
if (!$handle) {
throw new Exception("Could not read Web Storage Directory");
}
else{
while (false !== ($entry = readdir($handle))) {
$this->list_of_files[$entry] = filesize(WEB_STORAGE_DIR.DIRECTORY_SEPARATOR.$entry);
}
closedir($handle);
// Remove . and .. from the list
unset($this->list_of_files['.']);
unset($this->list_of_files['..']);
}
}
function is_empty() {
return empty($this->list_of_files);
}
}
我已添加error_reporting(E_ALL & ~E_NOTICE);
到示例中,因为这将确保您看到任何错误并可能有助于调试您的问题。更多信息在这里: http: //php.net/manual/en/function.error-reporting.php