Reputation: 2420
can someone pls fill me in on the correct syntax for this in PHP? I have:
function mainFunction($str,$thingToDoInMain){
$thingToDoInMain($str);
}
function printStr($str){
echo $str;
}
mainFunction("Hello",printStr);
I am running this on WAMP and I get an error/warning saying
use of undefined constant printStr - assumed 'printStr' on line 5
...and then I get "Hello" printed out as desired further down the page.
So, how do a refer to the function printStr
in the last line to get rid of warning? I have tried $printStr
, printStr()
and $printStr
. Thanks in advance.
Upvotes: 1
Views: 72
Reputation: 46900
Simply add a $
sign before your thingToDoInMain
function call making it a proper function name, because thingToDoInMain
itself is not a function name. Whereas the value contained in $thingToDoInMain
is a function name.
<?php
function mainFunction($str,$thingToDoInMain){
$thingToDoInMain($str); //Here $ is missing
}
function printStr($str){
echo $str;
}
mainFunction("Hello","printStr"); // And these quotes
?>
Upvotes: 5
Reputation: 799540
In PHP, function names are passed as strings.
mainFunction("Hello", "printStr");
Upvotes: 1