Php 未定义成员变量
我创建了以下类:Php 未定义成员变量,php,oop,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) {
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行的路径
致命错误未捕获错误:无法访问空属性 我不知道是什么导致了问题。您应该访问类似的
$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());
设置或获取属性时,不要使用美元符号。用
$this->path
代替$this->$path
@rickdenhaan噢,该死的,谢谢你