ver*_*nti 3 php conditional if-statement modularity modularization
我试图模块化一个冗长的if..else功能.
$condition = "$a < $b";
if($condition)
{
$c++;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法将文字字符串翻译成逻辑表达式?
我试图模块化一个冗长的if..else函数.
您不需要将条件放在字符串中,只需存储布尔值true或false:
$condition = ($a < $b);
if($condition)
{
$c++;
}
Run Code Online (Sandbox Code Playgroud)
$ a和$ b的值可能会在$ condition的定义及其用法之间发生变化
一个解决方案是Closure(假设定义和用法发生在同一范围内):
$condition = function() use (&$a, &$b) {
return $a < $b;
}
$a = 1;
$b = 2;
if ($condition()) {
echo 'a is less than b';
}
Run Code Online (Sandbox Code Playgroud)
但我不知道这是否对你有意义而不知道你想要完成什么.