这会抛出一个错误:
class foo
{
var $bar;
public function getBar()
{
return $this->Bar; // beware of capital 'B': "Fatal: unknown property".
}
}
但这不会:
class foo
{
var $bar;
public function setBar($val)
{
$this->Bar = $val; // beware of capital 'B': silently defines a new prop "Bar"
}
}
如何强制PHP在两种情况下抛出错误?我认为第二种情况比第一种情况更重要(因为我花了2个小时搜索d....)
你可以使用魔法方法
__set()在向不可访问的属性写入数据时运行。
__get()用于从不可访问的属性读取数据。
class foo
{
var $bar;
public function setBar($val)
{
$this->Bar = $val; // beware of capital 'B': silently defines a new prop "Bar"
}
public function __set($var, $val)
{
trigger_error("Property $var doesn't exists and cannot be set.", E_USER_ERROR);
}
public function __get($var)
{
trigger_error("Property $var doesn't exists and cannot be get.", E_USER_ERROR);
}
}
$obj = new foo();
$obj->setBar('a');
会抛出错误
致命错误:属性栏不存在且无法设置。第13行
可以根据PHP的错误级别设置错误级别
我能想到的一个解决方案是(ab)使用__set
和property_exists
:
public function __set($var, $value) {
if (!property_exists($this, $var)) {
throw new Exception('Undefined property "'.$var.'" should be set to "'.$value.'"');
}
throw new Exception('Trying to set protected / private property "'.$var.'" to "'.$value.'" from invalid context');
}
演示:http://codepad.org/T5X6QKCI