作为函数参数的非原语类的PHP数组

作为函数参数的非原语类的PHP数组,php,Php,我想知道(如果可能的话)如何将非基本类的数组声明为函数参数。比如说 <?php class C {} function f(array C $c) { /* use $c[1], $c[2]... */ } 主要事实-当前您不能将提示参数键入为某物的数组 因此,您可以选择: // just a function with some argument, // you have to check whether it is array // and whether each i

我想知道(如果可能的话)如何将非基本类的数组声明为函数参数。比如说

<?php
class C {}

function f(array C $c) {
    /* use $c[1], $c[2]... */
}

主要事实-当前您不能将提示参数键入为某物的
数组

因此,您可以选择:

// just a function with some argument, 
// you have to check whether it is array 
// and whether each item in this array has type `C`
function f($c) {} 

// function, which argument MUST be array.
// if it is not array - error happens
// you still have to check whether 
// each item in this array has type `C`
function f(array $c) {} 

// function, which argument of type CCollection
// So you have to define some class CCollection
// object of this class can store only `C` objects
function f(CCollection $c) {} 

// class CCollection can be something like
class CCollection 
{
    private $storage = [];

    function addItem(C $item)
    {
        $this->storage[] = $item;
    }

    function getItems()
    {
        return $this->storage;
    }
}

不需要为
$c
声明任何类型,您可以直接执行
函数f($c){…}
,因为
$c
是c类对象的数组。这是不可能的。或者创建一个类,如
CCollection
,它将存储
C
对象的集合,您不需要在参数中添加“array”。您所需要做的就是添加要传递的对象的类型,在本例中是类C,因此:
函数f(C$C){..}
@CodeGodie参数必须是C objectsAhh的数组。。gotcha@u_mulder感谢您的澄清。PHP7.1支持
iterable
类型提示: