指定形參類型是PHP 5就支持的一項特性。形參支持array - 數組、 object - 對象兩種類型。
class User{
public $name;
public $password;
function __construct($name,$password){
$this->name=$name;
$this->password=$password;
}
}
//參數可以指定對象類型
function f1(User $user){
echo $user->name,”,”,$user->password;
}
//參數可以指定數組類型
function f2(array $arr){}
//參數不可以指定基本類型,下面一句會出錯
function f3(string $s){}
那對於我們最常見的需求,如強制參數類型是字符串或整型,怎么辦呢?
在不考慮轉換到Facebook的HHVM運行環境下的前提下,就用不了Hack語言。在沒有Hack語言的情況下,就得自行定義一些基本類型類來完成相應的功能。
以下代碼純屬思考,未經項目實證,對於相應性能或靈活性的影響需要在項目中實戰評估。
class CString {
private $_val = '';
public function __construct($str = '') {
if (!is_string($str)) {
throw new Exception('Illegal data type');
}
$this->_val = $str;
}
public function __toString() {
return $this->_val;
}
}
class CInteger {
private $_val = 0;
public function __construct($str = 0) {
if (!is_int($str)) {
throw new Exception('Illegal data type');
}
$this->_val = $str;
}
public function __toString() {
return (string) $this->_val;
}
}
實際調用函數
function findUserByName(CString $name) {
$sql = '....' . $name;
//code
}
function findUserById(CInteger $id) {
$sql = '.... AND uid=' . $id;
//code
}
再往前走,對於集合型的數據呢? Yii框架中定義過一些相關的集合類,基本可以解決此類問題。
如CTypedList:
class CTypedList extends CList
{
private $_type;
/**
* Constructor.
* @param string $type class type
*/
public function __construct($type)
{
$this->_type=$type;
}
/**
* Inserts an item at the specified position.
* This method overrides the parent implementation by
* checking the item to be inserted is of certain type.
* @param integer $index the specified position.
* @param mixed $item new item
* @throws CException If the index specified exceeds the bound,
* the list is read-only or the element is not of the expected type.
*/
public function insertAt($index,$item)
{
if($item instanceof $this->_type)
parent::insertAt($index,$item);
else
throw new CException(Yii::t('yii','CTypedList<{type}> can only hold objects of {type} class.',
array('{type}'=>$this->_type)));
}
}
而對於單純的數組,能怎么辦呢?