未定义的成员变量

时间:2018-03-18 16:25:55

标签: php oop

我已经创建了以下课程:

class NotFoundException extends Exception {}
class Foo{
    private $path;
    private $array;

    public static function load($name) {
        try {
            return new Foo($name);
        } catch (NotFoundException $unfe) {
            return null;
        }
    }

    public function __construct($name){
        if (true){
            $this->$path = 'public_html/'.$name.'/';
            $this->$array= array('1','2','3');
        }
        else
            throw new NotFoundException();
    }

    public function getArray(){
        return $this->$array;
    }
}
$foo = Foo::load('first');
print_r($foo->getArray());

当我运行我的代码时,我得到了 注意未定义的变量:第18行的路径
致命错误未捕获错误:无法访问空属性

我不知道造成这个问题的原因。

1 个答案:

答案 0 :(得分:2)

您应该访问$this->path $this->array,例如$class NotFoundException extends Exception {} class Foo{ private $path; private $array; public static function load($name) { try { return new Foo($name); } catch (NotFoundException $unfe) { return null; } } public function __construct($name){ if (true){ $this->path = 'public_html/'.$name.'/'; $this->array= array('1','2','3'); } else throw new NotFoundException(); } public function getArray(){ return $this->array; } } $foo = Foo::load('first'); print_r($foo->getArray()); ,而无需预先C++ cli

您可以将代码更新为:

C#
相关问题