Iterable objects and array type hinting?

前端 未结 6 1593
遇见更好的自我
遇见更好的自我 2020-11-30 03:28

I have a lot of functions that either have type hinting for arrays or use is_array() to check the array-ness of a variable.

Now I\'m starting to use ob

6条回答
  •  醉酒成梦
    2020-11-30 04:15

    You CAN use type hinting if you switch to using iterable objects.

    protected function doSomethingWithIterableObject(Iterator $iterableObject) {}
    

    or

    protected function doSomethingWithIterableObject(Traversable $iterableObject) {}
    

    However, this can not be used to accept iterable objects and arrays at the same time. If you really want to do that could try building a wrapper function something like this:

    // generic function (use name of original function) for old code
    // (new code may call the appropriate function directly)
    public function doSomethingIterable($iterable)
    {
        if (is_array($iterable)) {
            return $this->doSomethingIterableWithArray($iterable);
        }
        if ($iterable instanceof Traversable) {
            return $this->doSomethingIterableWithObject($iterable);
        }
        return null;
    }
    public function doSomethingIterableWithArray(array $iterable)
    {
        return $this->myIterableFunction($iterable);
    }
    public function doSomethingIterableWithObject(Iterator $iterable)
    {
        return $this->myIterableFunction($iterable);
    }
    protected function myIterableFunction($iterable)
    {
        // no type checking here
        $result = null;
        foreach ($iterable as $item)
        {
            // do stuff
        }
        return $result;
    }
    

提交回复
热议问题