Jon
Jon

Reputation: 2420

PHP Passing function as a parameter syntax

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

Answers (2)

Hanky Panky
Hanky Panky

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
?>

Demo

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799540

In PHP, function names are passed as strings.

mainFunction("Hello", "printStr");

Upvotes: 1

Related Questions