私有数组$list_of_files
保持未初始化状态。如何从while循环更新它?
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($list_of_files['.']);
unset($list_of_files['..']);
}
}
function is_empty() {
return empty($list_of_files);
}
}
答案 0 :(得分:0)
访问属性,您需要使用$this
,否则您将创建一个局部变量。你在一个地方这样做,但是例如不在这里
return empty($list_of_files);
由于该变量从未设置过,因此总会返回相同的内容。
return empty($this->list_of_files);
对于该属性的其他引用也是如此,制作完整的代码(当然,这是未经测试的,因为你没有提供任何可测试的东西)看起来像这样
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);
}
}
答案 1 :(得分:0)
$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