2012-08-15 128 views
1

我愿做这样的事情:是否可以定义args中所需的数组类型?

class CCC {} 
function abc(array of CCC $variable) 

这可能在PHP?

+3

简短的答案是否定的。 ) – raina77ow 2012-08-15 12:27:39

+0

部分匹配:[类型检查所有数组元素](http://stackoverflow.com/questions/2323013/type-check-in-all-array-elements) – Leigh 2012-08-15 12:32:58

+0

...和长的答案取决于为什么做你需要这个。如果足以在运行时检查参数,则deceze的答案适合您。但是,如果你需要的是IDE的帮助,我建议检查[这个线程](http://stackoverflow.com/questions/778564/phpdoc-type-hinting-for-array-of-objects)以获得大量有用的提示。 ) – raina77ow 2012-08-15 12:39:25

回答

6

你需要手动检查:

function foo(array $arr) { 
    if (array_filter($arr, function ($i) { return !($i instanceof CCC); })) { 
     throw new InvalidArgumentException('Array must contain instances of CCC'); 
    } 

    ... 
} 
+0

thx,很好的答案 – 2012-08-15 12:48:14

相关问题