开发者

Exception instead Notice

开发者 https://www.devze.com 2023-01-17 08:08 出处:网络
I have two classes: class Test { public $name; } /*******/ class MyClass { private $_test = NULL; __get(开发者_高级运维$name)

I have two classes:

class Test {
  public $name;
}

/*******/

class MyClass {
  private $_test = NULL;

  __get(开发者_高级运维$name)
  {
    return $this->$name;
  }

  __set($name,$value)
  {
    $this->$name = $value;
  }
}

And when I want to use it this way:

$obj1 = new MyClass();
$obj1->_test = new Test();
$obj1->_test->name = 'Test!';

Everything is ok. But it is also possible, that someone might use it this way:

$obj1 = new MyClass();
$obj1->_test->name = 'Test!';

Then I get notice "Notice: Indirect modification of overloaded property MyClass::$_test has no effect in /not_important_path_here". Instead that notice I want to throw an Exception. How to do it?


What you're looking for is the ErrorException object.

function exception_error_handler($no, $str, $file, $line ) { throw new ErrorException($str, 0, $no, $file, $line); }
set_error_handler("exception_error_handler");


In your __get() method check to see if $_test is an instance of Test. If it is return it, otherwise throw the exception in the __get() method.

0

精彩评论

暂无评论...
验证码 换一张
取 消