【问题标题】:How should my PHP function handle invalid parameters?我的 PHP 函数应该如何处理无效参数?
【发布时间】:2012-01-16 11:14:27
【问题描述】:

我正在创建一些可重用的函数,现在我有这样的错误处理设置:

<?php
...
public function insertAfter( $index, $objects )
{
    if ( ! is_int( $index ) ) {
        trigger_error( 'Cursor::insertAfter() expects parameter 1 to be integer, ' . gettype( $index ) . ' given', E_USER_WARNING );
    } else {
        // Do my regular code
    }

    return $this;
}
...

我尝试将其设置为像 PHP 处理错误一样工作。这是一种合适的做事方式吗?

【问题讨论】:

    标签: php


    【解决方案1】:

    【讨论】:

    • 我本来就有这个,但我不想在代码中乱扔try catch语句
    • InvalidArgumentException 是最合适的。
    • @Rogue 您不必捕获这样的异常,这就是重点。传递一个 invalid 参数类型不应该被捕获,它是一个异常错误,应该停止你的程序并引导你修复你的代码.
    • @deceze 感谢您指出InvalidArgumentException,这正是我想要的。另外,感谢您澄清例外情况。
    【解决方案2】:

    查看Altumo 包。它有很多方便的验证器来做你想做的事情。

    例如,

    $index = \Altumo\Validation\Numerics::assertInteger( 
        $index, 
        'Cursor::insertAfter() expects parameter 1 to be integer, ' . gettype( $index ) . ' given'
    );
    

    对象类型、字符串、布尔值等有validators

    附:异常比 trigger_error() 更灵活,因为您可以更精细地控制它们。 Here's a good thread on that topic.

    【讨论】:

      猜你喜欢
      • 2011-10-28
      • 2023-02-05
      • 1970-01-01
      • 2012-07-01
      • 2018-08-01
      • 1970-01-01
      • 2021-04-10
      • 2011-04-17
      • 1970-01-01
      相关资源
      最近更新 更多