You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP类出现Undefined member variable错误,求排查解决

排查Undefined member variable错误的原因

嗨,我一眼就发现问题啦——你在访问类的成员变量时误用了可变变量的语法!

看你代码里这些出错的地方:

$this->$path = 'public_html/'.$name.'/';
$this->$array= array('1','2','3');
// 还有getArray方法里的
return $this->$array;

在PHP中,访问类成员变量的正确写法是$this->变量名,而$this->$变量名是可变变量的用法——它会把$变量名的值当作成员变量的名字来访问,但你这里并没有定义$path或$array这类普通变量,所以PHP才会抛出“Undefined member variable”的错误。

只需要把每个$this->$xxx里的第二个$去掉,就能解决问题。修正后的完整代码如下:

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());

这样修改后,PHP就能正确识别你要访问的是类中预先定义的$path和$array成员变量,错误也就消失啦。

内容的提问来源于stack exchange,提问作者Quest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:34:39