【问题标题】:Pass Comparison Operator through Function Argument通过函数参数传递比较运算符
【发布时间】:2016-12-21 02:04:21
【问题描述】:

我希望我的函数有一个比较运算符作为参数(或者最好是作为参数的一部分,例如 >0 ):

代替

function comps($a,$b){
    if ($a > $b)
      echo "This works.";
}
comps(1,0);

我希望能够做类似的事情

function comps($a,$b){
    if ($a $b)
      echo "This works.";
}
comps(1,'>0');

一段时间以来,我一直在用头撞墙。我尝试了不同的迭代:

"/>0"
'>' . 0
(string)> 0

以及尝试将比较运算符作为第三个参数。

实际使用是:

function mysort($key,$match){
$temp_array = array();
global $students;

foreach ($students as $row) {
    if($row[$key] > $match ) 
    $temp_array[]= $row;
    }

foreach ($temp_array as $row) {
    echo $row['email'] . ', ';
    }
}
mysort('suzuki', '0'); 

谢谢

【问题讨论】:

  • 1) 为运算符使用第三个参数 2) 使用 switch 语句来确定需要使用哪个运算符执行哪些代码。
  • 不确定我是否需要同时执行这两个操作,但我确实尝试了第 1 步。我会添加清楚。
  • 有些重复,但我不需要动态部分。不知道如何分解该解决方案(或者它是否对我有用),但我会开始检查它。

标签: php function arguments comparison-operators


【解决方案1】:

你可以做一个返回类型的函数,随心所欲地使用。

我会为你做一个如下的函数:

<?php
    function getCond($a, $b, $both) {
        $data = false;
        if($both) {
            if($a == b) {
                $data = true;
            }
        }else {
             if($a > $b) {
                 $data = true;
             }
        }
        return $data;
    }

 /*  Use Your Function  */
    if (getCond(10, 5, true)) {      // condition for 10 == 5 and according to passed values you get false result in condition 
        echo "you result";
    } else if (getCond(10, 5, false)) {  // condition for 10 > 5 and according to passed values you get false result in condition
        echo "your result";
    } else if (getCond(6, 5, false)){    // condition for 6 > 5 and according to passed values you get true result in condition
        echo "your result";
    } 
?>

您也可以根据需要修改此功能:)

【讨论】:

    【解决方案2】:

    我使用的最简单的解决方案似乎是:

    function comps($a,$b,$c){
    if ($a > $b  and $a < $c)
    echo "True";
    }
    
    comps(1,0,2);
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-03
      • 2011-11-24
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 2018-10-28
      • 1970-01-01
      相关资源
      最近更新 更多