【问题标题】:function as parametr in function作为函数中的参数函数
【发布时间】:2017-02-11 16:26:30
【问题描述】:

我需要给函数作为参数函数。 例如

<i>$smoothFunc = smooth(function ($sum) {
  return sin(rad2deg($sum));
}, 15);

$smoothFunc(10) // ~ 0.438

我该怎么做?

此代码无效

$arg1=function($a,$b){
  return $a+$b;
};

function smoothFunc($arg1, $dx){
  return $f1($a,$b)+$dx;
};

echo (smoothFunc(arg1(2,3),1));*/

【问题讨论】:

  • 调用未定义函数arg12() 那么arg12() 函数在哪里

标签: php function arguments


【解决方案1】:

为了可用性单独创建函数!

function smooth($sum) {
    return sin(rad2deg($sum));
}
$smoothFunc = smooth(10);

【讨论】:

    【解决方案2】:
    <?php
    function arg1($a,$b){
      return $a+$b;
    };
    
    function smoothFunc($pArg1, $pDx){
      return $pArg1+$pDx;
    };
    
    echo (smoothFunc(arg1(2,3),1));
    

    【讨论】:

      【解决方案3】:
      <?php
      
      function arg12($a,$b){
        return $a+$b;
      };
      function f1($a,$b){
          return $a+$b;
      }
      function smoothFunc($a, $b, $dx){
        return f1($a,$b)+$dx;
      };
      
      echo (smoothFunc(arg12(2,3), 2, 1));
      

      请不要将函数关联到变量中并创建具有首位"$" 的函数。

      更多详情在这里http://php.net/manual/en/functions.user-defined.php

      【讨论】:

      • 您可以在javascript中将函数分配给变量。