(PHP)字符串变量作为if表达式(字符串$ other_variable名称也是)

时间:2015-08-15 05:48:35

标签: php string if-statement expression eval

所以我有这段代码:

$age = 23;
    $gender = 0;

    $rules = "gender = 0 AND ( age >= 2 AND age <= 20 )";
    $find = array(
      ' = ',
      'age',
      'gender'
    );
    $replace = array(
      ' === ',
      '$age',
      '$gender'
    );
    $rules = str_replace($find, $replace, $rules);
    print($rules);
    if (eval('return' . $rules . ';')) {
      return "You get coupon " . $coupon->couponID . "!";
    } else {
      return "Coupon " . $coupon->couponID . " is not for you!";
    }

我想要做的是将字符串变量用作我的if表达式。这可能吗?或者有更好的方法来实现这一目标吗?

1 个答案:

答案 0 :(得分:0)

修正了它。问题是===作为比较。当我使用==时,它有效!

现在是代码。

$rules = "$age >= 2 AND $age <= 20 AND ( $gender = 1 OR $gender = 2 )";
    $find = array(
      ' = ',
      'age',
      'gender'
    );
    $replace = array(
      ' == ',
      '$age',
      '$gender'
    );
    $rules = str_replace($find, $replace, $rules);
    print($rules);
    if (eval(sprintf('return (%s);', $rules))) {
      return "You get coupon " . $coupon->couponID . "!";
    } else {
      return "Coupon " . $coupon->couponID . " is not for you!";
    }