0

Let's say you are building an API that other people will work with. And you use typehinting a lot for functions, like function foo(array $arg){...}. This forces the argument to be an array, so passing traversable objects to this function won't work. But your function can work with such objects.

Do you think it's a good idea to remove the hint and handle traversable objects too? Or should I leave that to the user? (she can use iterator_to_array for example)

4

1 回答 1

1

您可能会删除我认为的类型提示并添加 PHPDoc 注释。说它需要一个数组,一个可遍历的甚至是数组访问。

用户在使用您的 API 时给予灵活性还不错,但是在处理不属于适当类型的参数时,您的 API 应该具有容错能力。因此,如果您删除类型提示,您应该将类​​型控件添加到您的方法中(当然您不必这样做,但它可能被认为是最佳实践)。但是进行检查会导致您的 API 变慢(它可能是疏忽的,并且可能被视为微优化,但是如果您的 API 需要快速工作,您也应该考虑这一点)。

于 2013-03-21T15:50:45.777 回答