PHP Traversable type hint

前端 未结 4 1647
-上瘾入骨i
-上瘾入骨i 2021-01-03 23:15

I have a relatively simple function which uses a foreach

function foo($t) {
     $result;
     foreach($t as $val) {
         $result = dosometh         


        
4条回答
  •  情书的邮戳
    2021-01-03 23:45

    Same problem. I've given up I simply manually code everything in the function.

    This should give you the functionality you want:

    function MyFunction($traversable)
    {
        if(!$traversable instanceof Traversable && !is_array($traversable))
        {
            throw new InvalidArgumentException(sprintf(
                'Myfunction($traversable = %s): Invalid argument $traversable.'
                ,var_export($traversable, true)
           ));
        }
    }
    

    EDIT

    If you only want to display type of $traversable. And if you want the functionality inheritable in child classes.

    public function MyMethod($traversable)
    {
        if(!$traversable instanceof Traversable && !is_array($traversable))
        {
            throw new InvalidArgumentException(sprintf(
                '%s::MyMethod($traversable): Invalid argument $traversable of type `%s`.'
                ,get_class($this)
                ,gettype($traversable)
           ));
        }
    }
    

提交回复
热议问题