从函数

时间:2015-08-24 21:21:40

标签: php if-statement

我有一个if语句,它在两个不同的函数中用于相同的条件。问题是条件最终会很长(5-7个OR)并且可能需要在将来进行修改。如果它们最终被修改,条件将在两个函数中以相同的方式改变。

一个if语句的示例:

if ($this->object === 'one' || $this->object === 'two' || $this->object === 'three' ) {
    echo 'Yes!';
} else {
    echo 'No!';
};

我正在考虑创建一个数组和一个将输入if语句的函数,但是无法想出任何方法来获取if语句来检查条件而不是检查是否存在输入。

$this->object = 'one';
$test_array = array('one', 'two', 'three');

function stmbuilder($array) {
    $count = count($array);
    $stm = '';

    for ($i = 0; $i < $count; $i++) {
        $intro = '$this->object ===';
        $connector = ($i < $count-1 ? ' || ' : '');
        $stm .= $intro . $array[$i] . $connector;
    }

    return $stm;
}

$condition = stmbuilder($test_array);

if ($condition) {
    echo 'Yes!';
} else {
    echo 'No!';
} //Will always echo Yes! since $condition has a value but does not check against what $this->object is

感谢任何帮助!

1 个答案:

答案 0 :(得分:4)

为什么不只是in_array()

$arr = array('one', 'two', 'three');

in_array('four', $arr) -> false
in_array('two', $arr) -> true
相关问题