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

通过指定函数/方法形参类型提高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)));
    }
}

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

本文来源:http://www.cnblogs.com/x3d/,转载请注明。

分类: 1 PHP

好文要顶;) 关注我;) 收藏该文;) ; "分享至新浪微博") ; "分享至微信")

x3d
关注 - 39
粉丝 - 96

+加关注;)

0

0

« 上一篇:Apache+Mod_Python配置
» 下一篇:LinuxMint 17.1 Cinnamon桌面窗口焦点bug

posted @ 2015-02-11 11:58 x3d 阅读(1444) 评论(1) 编辑 收藏


Original url: Access
Created at: 2018-11-29 19:02:21
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论