1

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.

2
  • There is no way in the world that this code can print Hello as it is, unless you made a typo. thingToDoInMain is not a valid function name. The value of that variable, $thingToDoInMain, is Commented Aug 30, 2013 at 5:07
  • Yeah. I made a typo. Have edited. Commented Aug 30, 2013 at 5:53

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

In PHP, function names are passed as strings.

mainFunction("Hello", "printStr");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.