简体   繁体   中英

How do you enforce your PHP method arguments?

你如何验证/管理你的PHP方法参数,为什么这样做?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM