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
相关产品推荐
相关产品推荐

