1
我在想(如果可能)你將如何聲明一個非原始類的數組作爲函數參數。例如作爲函數參數的非原始類的PHP數組
<?php
class C {}
function f(array C $c) {
/* use $c[1], $c[2]... */
}
我在想(如果可能)你將如何聲明一個非原始類的數組作爲函數參數。例如作爲函數參數的非原始類的PHP數組
<?php
class C {}
function f(array C $c) {
/* use $c[1], $c[2]... */
}
幫主 - 目前不能鍵入提示參數作爲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;
}
}
PHP7.1支持'iterable'類型提示:https://wiki.php.net/rfc/iterable – Philipp
沒有必要聲明任何類型'$ C',你可以直接做'函數f($ C){...}',因爲'$ c'是* C類*對象的數組。 –
沒辦法。或者創建一個像'CCollection'這樣的類,它將存儲'C'對象的集合 –
您不需要在參數中添加「數組」。所有你需要做的就是添加你傳遞的對象的類型,在這種情況下是類C,因爲:'function f(C $ c){..}' – CodeGodie