php - 限制函数参数以允许特定值

标签 php function

这个问题在这里已经有了答案:





Enumerations on PHP

(39 个回答)


9 个月前关闭。




我想限制某人可以在我的函数调用中分配给变量的值。
例如说我的功能是

function myFunction ($carType, $isOld , $something)
{
    //do what is required
}

我希望我应该能够限制 $carType, $isOld 只有某些值,例如来自给定数组:
$carTypeValues = array ("car1", "car2", "car3");
$isOldValues = array (true,false);

我知道我可以将参数变量限制为某个类类型。

我试图找到一种方法来做到这一点,但我找不到任何能解决我想要的问题的方法。我知道我可以在实际执行函数调用后检查该值,但是我正在寻找一些可以让用户最好能够使用选择器的东西,例如:
myFunction (carType::car1, isOld::car2 , $something);

我不确定,这可能是:
myFunction (carType.car1, isOld.car2 , $something);

感谢您阅读本文

最佳答案

您是否正在寻找一种简单的验证方式来验证传递到函数中的变量,例如这样?

function myFunction ($carType = null, $isOld = null, $something = null)
{
    $carTypeValues = array ("car1", "car2", "car3");
    $isOldValues = array (true,false);

    $strict = true; // strict comparison here? e.g. null == false if $strict is false

    if(
        !$carType || !$isOld                            // variables aren't empty?
        || !in_array($carType, $carTypeValues, $strict) // passed carType is ok?
        || !in_array($isOld, $isOldValues, $strict)     // passed isOld is ok?
    ) {
        // error, incorrect variable passed
        return false;
    }

    //do what is required
    return true;
}

这将允许您检查 A. 您传递的变量存在,并且 B. 它们存在于您定义的一系列可接受的选项中。

I know I can check the value once I actually execute the function call, however I am looking for something that will allow the user to preferably be able to use selectors



您不能像示例中那样指定选择器,但您可以传入一个整数来表示数组键,从而避免复制变量的值:
function myFunction($carType = null, $isOld = null, $something = null) { 
    $carTypeValues = array ("car1", "car2", "car3");
    $isOldValues = array (true,false);  

    if(
        !$carType || $isOld
        || !array_key_exists($carType, $carTypeValues)
        || !array_key_exists($isOld, $isOldValues)
    ) {
        return false;
    }

    // handle OK
    return array(
        'car_type' => $carTypeValues[$carType],
        'is_old'   => $isOldValues[$isOld]
    );
}

myFunction(1, 0, 'foobar'); // array('car_type' => 'car2', 'is_old' => true);

关于php - 限制函数参数以允许特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24688847/

相关文章:

python - 迭代与Python中的列表对应的字典键值

python - 将列表转换为字符串

PHP:调用未定义的函数 gzdecode()

php - Google Calendar API v3 无法添加事件 php

javascript - 带有远程结果和缓存的 jQuery 类别搜索

php - 在 HTML 表格中打印查询

javascript - AS2 - 获取 JavaScript 变量值

php - 需要有关 PHP/MySQL 架构的建议

php - 如果 url 包含使用 htaccess 的特定字符串,则重定向

javascript - 使用按钮更改 javascript 变量