简体   繁体   English

你如何强制执行PHP方法参数?

[英]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. 如果它只期望一个数组,我使用带有array关键字的type-hinting。

     public function foo(array $bar) 
  3. If it's expecting a string, int, bool or float, I cast it: 如果它期望一个字符串,int,bool或float,我将它转换为:

     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 : 如果它需要文件名或目录,只需用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. Typechecking是你应该在开发阶段做的事情,而不是生产。 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. 动态类型化的PHP可以很好地适应不同的值。 There are only few spots where you want to turndown the basic language behaviour. 只有少数几个地方你想要调整基本的语言行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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