你可以使用魔法
__set() is run when writing data to inaccessible properties.
__get() is utilized for reading data from inaccessible properties.
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');
它会抛出错误
Fatal error: Property Bar doesn’t exists and cannot be set. on line 13