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

时间:2017-01-22 18:24:15

标签: php

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

<?php
class C {}

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

1 个答案:

答案 0 :(得分:1)

主要事实 - 目前您不能将提示参数键入array of something

所以你可以选择:

// 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;
    }
}