在方法1中设置后,属性在方法2中为null

时间:2011-12-06 17:22:55

标签: php methods

希望你能帮我解决这个问题!

的index.php

include_once 'files.class.php';
$file_object = new FileObject('resources');
$file_object->ReturnCurrentDirectoryList();

files.class.php

class FileObject{
public $directory_list;

    function __construct($current_directory_in){
        $this->directory_list = $this->BuildCurrentDirectoryList($current_directory_in);
    }

    function BuildCurrentDirectoryList($current_directory_in){
        $i = 0;
        $iterator = new DirectoryIterator($current_directory_in);

        foreach ($iterator as $fileinfo){
            if ($fileinfo->isDir()){
                $this->directory_list[$i]['pathname'] = $fileinfo->getPathname();
            }elseif($fileinfo->isFile()){
                $this->directory_list[$i]['filename'] = $fileinfo->getFilename();
            }
            $i++;
        }
    }

    function ReturnCurrentDirectoryList(){
        var_dump($this->directory_list);
    }
}

在所有这些结束时,返回的是

null

返回的是

array  0 =>  array 'pathname' => string 'resources\.',  1 => array 'pathname' => string 'resources\..', 2 =>  array 'pathname' => string 'resources\Images'

我对类/方法有些新意。

2 个答案:

答案 0 :(得分:3)

这是错误的:

$this->directory_list = $this->BuildCurrentDirectoryList($current_directory_in);

您已分配给$this->directory_list,但BuildCurrentDirectoryList不会返回任何内容。该功能只有副作用,没有返回值。

删除赋值,以便构造函数看起来像这样,你应该好好去:

$this->directory_list = array(); //I like to initialise arrays to the empty array
$this->BuildCurrentDirectoryList($current_directory_in);

答案 1 :(得分:1)

在构造函数中,您将directory_list分配给BuildCurrentDirectoryList的返回,但是您没有在BuildCurrentDirectoryList中返回任何内容,而是直接在该方法中分配directory_list。最后,BuildCurrentDirectoryList返回NULL。所以,要么返回directory_list,要么就是不要像这样分配它:

function __construct($current_directory_in){
    $this->BuildCurrentDirectoryList($current_directory_in);
}
相关问题