【问题标题】:How do you enforce your PHP method arguments?你如何执行你的 PHP 方法参数?
【发布时间】:2011-06-07 07:47:10
【问题描述】:

您如何验证/管理您的 PHP 方法参数以及为什么要这样做?

【问题讨论】:

标签: php parameters methods


【解决方案1】:

类型检查应该在开发阶段进行,而不是在生产阶段。所以合适的句法特征是:

 function xyz($a, $b) {
     assert(is_array($a));
     assert(is_scalar($b));

但是我会尽量避免它,或者最好使用类型强制。动态类型的 PHP 可以很好地适应不同的值。只有少数几个地方可以拒绝基本的语言行为。

【讨论】:

  • 有效,但不是很好。请参阅the docs on assert 并阅读以下摘录:Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated. 但如果仅用于调试,那么它可以工作...
  • @ircmaxell:这就是我对Typechecking is something you should do at the development stage, not in production 的意思。如果仍然需要在运行时检查类型,那么我会猜测更严重的结构问题;类型检查不太可能解决的问题。在开发时应该检测到这些东西(我在理论上将其比作严格类型语言的编译阶段)。所以它确实应该算作调试或单元测试的长臂。
【解决方案2】:

好吧,假设您在谈论类型检查方法参数,这取决于:

  1. 如果它需要一个对象,我使用type-hinting 和一个接口:

    public function foo(iBar $bar)
    
  2. 如果它只需要一个数组,我会使用带有 array 关键字的类型提示。

    public function foo(array $bar)
    
  3. 如果它需要一个字符串、int、bool 或 float,我将其转换为:

    public function foo($bar) {
        $bar = (int) $bar;
    }
    
  4. 如果预期混合,我只需检查级联:

    public function foo($bar) {
        if (is_string($bar)) {
            //handle string case
        } elseif (is_array($bar)) {
            //...
        } else {
            throw new InvalidArgumentException("invalid type");
        }
    }
    
  5. 最后,如果它需要一个可迭代的类型,我不使用类型提示。我先检查它是否是一个数组,然后重新加载迭代器:

    public function foo($bar) {
        if (is_array($bar)) {
            $bar = new ArrayIterator($bar);
        }
        if (!$bar instanceof Traversable) {
            throw new InvalidArgumentException("Not an Iterator");
        }
    }
    
  6. 如果需要文件名或目录,只需使用is_file 确认即可:

    public function foo($bar) {
        if (!is_file($bar)) {
            throw new InvalidArgumentException("File doesn't exist");
        }
    }
    

我认为这可以处理大多数情况。如果你想到任何其他人,我很乐意回答他们......

【讨论】:

  • 谢谢,我正在寻找一堆这样的例子。
猜你喜欢
  • 2012-02-28
  • 2014-06-14
  • 2018-06-14
  • 1970-01-01
  • 2019-04-12
  • 2011-11-24
  • 1970-01-01
  • 2016-09-20
  • 1970-01-01
相关资源
最近更新 更多