如果未将值传递给方法,则抛出异常

时间:2014-06-22 13:17:57

标签: php oop exception

如果没有将值传递给方法,是否可以抛出异常,而不仅仅是普通的PHP错误?

$obj=new foo();
$obj->bar(null); //This is okay
$obj->bar();     //This should throw an error

class foo {
   public function bar($value) {}
}

2 个答案:

答案 0 :(得分:2)

我们自己处理缺失的参数似乎不是最好的想法(我们有默认值),但我感兴趣的是如何实现这一点。在寻找解决方案之后,我提出了以下建议:

<?php

class foo {

    function warning_handler($errno, $errstr) {
        // just compare the strings because we don't have particular warning number
        if (strpos($errstr, 'Missing argument 1') === 0) {
            // throw exception or do whatever you want to handle this situation
            throw new Exception('Custom handler: First argument is missing');
        }
        // execute original error handler
        return false;
    }

    function __call($name, $arguments) {
        // if required, check whether method exists, before calling
        // if required, check whether particular method should be wrapped
        set_error_handler(array($this, 'warning_handler'), E_WARNING);
        call_user_func_array(array($this, $name), $arguments);
        restore_error_handler();
    }

    // should not be public, because "__call" will not work
    protected function bar($value) {
        // ...
    }
}

$obj = new foo();
try {
    // calling without arguments will throw custom exception
    $obj->bar();
} catch (Exception $e) {
    echo $e->getMessage();
}

创意来源:Can I try/catch a warning?

答案 1 :(得分:0)

当然,当你编码时

class foo {
   public function bar($value) {
       echo 'You called';
   }
}

$obj=new foo();
$obj->bar(null); //This is okay
$obj->bar();     //This should throw an error

测试时结果如下。

You called
Warning: Missing argument 1 for foo::bar(), called in D:\PHP_SOURCE\tst.php on line 12 and defined in D:\PHP_SOURCE\tst.php on line 4

所以你知道你做错了什么!

但是如果你想亲自测试参数的存在,但NULL是一个有效的参数,你不能这样做,因为&#39; $ obj-&gt; bar();&#39;相当于$obj->bar(null);

所以你要做的就是让参数的默认值永远不能在那个参数中传递,就像这样

class foo {
   public function bar($value='The Impossible') {
       if ( $value == 'The Impossible' ) {
          throw new Exception('Holy Cow Batman, The Impossible just happened');
       }
       echo 'You called' . PHP_EOL;
   }
}


try {
    $obj=new foo();
    $obj->bar(null); //This is okay
    $obj->bar();     //This should throw an error
}
catch (Exception $e ) {
    echo $e->getMessage();
}

将抛出所需的异常。

You called
Holy Cow Batman, The Impossible just happened

因此,如果事实上可以实现这种情况,你可以捕捉和管理这种情况。