php封装参数检查

2021年5月1日09:30:23

 

if (!function_exists('parameterCheck')) {

    /**
     * 如果是double的话,也使用float,需要处理其他类型数据自己添加
     * @param type $param 需要处理的参数
     * @param type $ExpectDataType  期望返回数据类型
     * @param type $defaultValue  如果没有值返回的默认值
     * @return type
     * @throws \Exception
     */
    function parameterCheck($param, $ExpectDataType, $defaultValue) {
        $dataType = ['int', 'float', 'string', 'array'];
        if (!in_array($ExpectDataType, $dataType)) {
            throw new \Exception('数据类型不存在');
        }
        if (empty($param)) {
            return $defaultValue;
        }
        if ($ExpectDataType == 'int') {
            return (int) htmlFilter($param);
        } elseif ($ExpectDataType == 'float') {
            return (float) htmlFilter($param);
        } elseif ($ExpectDataType == 'string') {
            return (string) htmlFilter($param);
        } elseif ($ExpectDataType == 'array') {
            return (array) $param;
        }
    }

}

if (!function_exists('htmlFilter')) {

    /**
     * 
     * @param type $param 需要html转义和去除空格的参数
     * @throws \Exception
     */
    function htmlFilter($param) {
        return htmlspecialchars(trim($param), ENT_QUOTES, "UTF-8");
    }

}

 

posted on 2021-05-01 09:31  zh7314  阅读(86)  评论(0编辑  收藏  举报