php - Throw exception if value not passed to method -
php - Throw exception if value not passed to method -
instead of normal php error, possible throw exception if value not passed method?
$obj=new foo(); $obj->bar(null); //this okay $obj->bar(); //this should throw error class foo { public function bar($value) {} }
it seems not best thought handle missing arguments ourselves (we have default values that), interested how accomplish this. after looking solutions here , there, i've came following:
<?php class foo { function warning_handler($errno, $errstr) { // compare strings because don't have particular warning number if (strpos($errstr, 'missing argument 1') === 0) { // throw exception or whatever want handle situation throw new exception('custom handler: first argument missing'); } // execute original error handler homecoming false; } function __call($name, $arguments) { // if required, check whether method exists, before calling // if required, check whether particular method should wrapped set_error_handler(array($this, 'warning_handler'), e_warning); call_user_func_array(array($this, $name), $arguments); restore_error_handler(); } // should not public, because "__call" not work protected function bar($value) { // ... } } $obj = new foo(); seek { // calling without arguments throw custom exception $obj->bar(); } grab (exception $e) { echo $e->getmessage(); }
idea source: can try/catch warning?
php oop exception
Comments
Post a Comment