peter
peter

Reputation: 179

Exception instead Notice

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?

Upvotes: 1

Views: 931

Answers (2)

Jeff Hubbard
Jeff Hubbard

Reputation: 9902

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");

Upvotes: 4

Jeremy
Jeremy

Reputation: 2669

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.

Upvotes: 0

Related Questions