【问题标题】:PHP Passing function as a parameter syntaxPHP 传递函数作为参数语法
【发布时间】:2013-08-30 04:58:27
【问题描述】:

有人可以在 PHP 中填写正确的语法吗?我有:

function mainFunction($str,$thingToDoInMain){
   $thingToDoInMain($str);
}

function printStr($str){
    echo $str;
}

mainFunction("Hello",printStr);

我在 WAMP 上运行它,我收到一个错误/警告说

使用未定义的常量 printStr - 在第 5 行假定为“printStr”

...然后我会根据需要在页面下方打印出“Hello”。

那么,如何引用最后一行中的函数printStr 来消除警告?我试过$printStrprintStr()$printStr。提前致谢。

【问题讨论】:

  • 除非你打错了,否则这段代码不可能按原样打印HellothingToDoInMain 不是有效的函数名。该变量的值,$thingToDoInMain,是
  • 是的。我打错了。已编辑。

标签: php function syntax


【解决方案1】:

只需在 thingToDoInMain 函数调用之前添加一个 $ 符号,使其成为正确的函数名称,因为 thingToDoInMain 本身不是函数名称。而$thingToDoInMain 中包含的值是一个函数名。

<?php
function mainFunction($str,$thingToDoInMain){
     $thingToDoInMain($str);   //Here $ is missing
}

function printStr($str){
    echo $str;
}

mainFunction("Hello","printStr");   // And these quotes
?>

Demo

【讨论】:

    【解决方案2】:

    在 PHP 中,函数名作为字符串传递。

    mainFunction("Hello", "printStr");
    

    【讨论】:

      猜你喜欢
      • 2018-07-06
      • 2023-04-02
      • 2019-11-23
      • 2011-05-11
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      • 2013-09-11
      • 1970-01-01
      相关资源
      最近更新 更多