强制PHP在undefined属性上抛出错误

Axe*_*hor 16 php

这会抛出一个错误:

class foo
{
   var $bar;

   public function getBar()
   {
      return $this->Bar; // beware of capital 'B': "Fatal:    unknown property".
   }

}
Run Code Online (Sandbox Code Playgroud)

但这不会:

class foo
{
   var $bar;

   public function setBar($val)
   {
      $this->Bar = $val; // beware of capital 'B': silently defines a new prop "Bar"
   }

}
Run Code Online (Sandbox Code Playgroud)

如何强制PHP在两种情况下抛出错误?我认为第二种情况比第一种情况更为重要(因为它花了我2个小时来搜索属性中的一个错误的拼写错误).

Rob*_*ert 14

你可以使用魔术方法

将数据写入不可访问的属性时运行__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');
Run Code Online (Sandbox Code Playgroud)

它会抛出错误

致命错误:属性栏不存在且无法设置.在第13行

您可以根据PHP错误级别设置错误级别


Tim*_*lla 11

我能想象的一个解决方案是(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');
}
Run Code Online (Sandbox Code Playgroud)

演示:http://codepad.org/T5X6QKCI