How can I make PHP handle functions' overloading errors?
Lets assume I have a class called Form
. This class uses the magic method __call()
to add fields to itself like so:
<?php
class Form {
private $_fields = array();
public function __call($name, $args) {
// Only allow methods which begin with 'add'
if ( preg_m开发者_JS百科atch('/^add/', $name) ) {
// Add a new field
} else {
// PHP throw the default 'undefined method' error
}
}
}
My problem is that I can't figure out how to make PHP handle the calls to undefined methods in it's default way. Of course, the default behavior can be mimicked in many ways, for example I use the following code right now:
trigger_error('Call to undefined method ' . __CLASS__ . '::' . $function, E_USER_ERROR);
But I don't like this solution because the error itself or its level might change in the future, so is there a better way to handle this in PHP?
Update Seems like my question is a little vague, so to clarify more... How can I make PHP throw the default error for undefined methods without the need to supply the error and it's level? The following code won't work in PHP, but it's what I'm trying to do:
// This won't work because my class is not a subclass. If it were, the parent would have
// handled the error
parent::__call($name, $args);
// or is there a PHP function like...
trigger_default_error(E_Undefined_Method);
If anyone is familiar with ruby, this can be achieved by calling the super
method inside method_missing
. How can I replicate that in PHP?
Use exceptions, that's what they're for
public function __call($name, $args) {
// Only allow methods which begin with 'add'
if ( preg_match('/^add/', $name) ) {
// Add a new field
} else {
throw new BadMethodCallException('Call to undefined method ' . __CLASS__ . '::' . $name);
}
}
This is then trivially easy to catch
try {
$form->foo('bar');
} catch (BadMethodCallException $e) {
// exception caught here
$message = $e->getMessage();
}
If you want to change error level, just change it when necessary or add if statement instead of E_USER_ERROR
精彩评论