通过指定函数/方法形参类型提高PHP代码可靠性

指定形参类型是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)));
    }
}

而对于单纯的数组,能怎么办呢?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值