开发者

How do you enforce your PHP method arguments?

How do开发者_如何学Python you validate/manage your PHP method arguments and why do you do it this way?


Well, assuming that you're talking about type-checking method arguments, it depends:

  1. If it's expecting an object, I use type-hinting with an interface:

    public function foo(iBar $bar)
    
  2. If it's expecting an array only, I use type-hinting with the array keyword.

    public function foo(array $bar)
    
  3. If it's expecting a string, int, bool or float, I cast it:

    public function foo($bar) {
        $bar = (int) $bar;
    }
    
  4. If it's expecting mixed, I just check in a cascade:

    public function foo($bar) {
        if (is_string($bar)) {
            //handle string case
        } elseif (is_array($bar)) {
            //...
        } else {
            throw new InvalidArgumentException("invalid type");
        }
    }
    
  5. Lastly, if it's expecting an iterable type, I don't use type-hinting. I check if it's an array first, then re-load the iterator:

    public function foo($bar) {
        if (is_array($bar)) {
            $bar = new ArrayIterator($bar);
        }
        if (!$bar instanceof Traversable) {
            throw new InvalidArgumentException("Not an Iterator");
        }
    }
    
  6. If it's expecting a filename or directory, just confirm it with is_file:

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

I think that handles most of the cases. If you think of any others, I'll gladly try to answer them...


Typechecking is something you should do at the development stage, not in production. So the appropriate syntactic feature for that would be:

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

However I'll try to avoid it, or use type coercion preferrably. PHP being dynamically typed does quite well adapting to different values. There are only few spots where you want to turndown the basic language behaviour.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜