1

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

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

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

mainFunction("Hello",printStr);

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

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

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

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

4

2 回答 2

5

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

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

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

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

演示

于 2013-08-30T05:00:42.283 回答
1

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

mainFunction("Hello", "printStr");
于 2013-08-30T05:00:38.583 回答