0

Invalid code:

$functionName = 'sayThis';

function $functionName($string) {
    echo $string;
}

Can I do anything like this?

3
  • 1
    you really don't want to do this. horrible idea. Commented Nov 29, 2009 at 0:09
  • 1
    Would help to understand why you want to do this. What are you trying to accomplish? Commented Nov 29, 2009 at 0:20
  • I have the same function (processFormSubmission()) in many files. The function currently has one name, but does several different things depending on the file it is in. Sometimes the same function name can be included in one execution. If this is the case, I get an error saying that the function has already been declared. I want to dynamically name the function so I don't have name clashes. The dynamically assigned name of the function will be stored in a class. Commented Nov 29, 2009 at 8:03

2 Answers 2

3

call_user_func and call_user_func_array do something similar. Use sparingly and judiciously.

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

1 Comment

I want to dynamically declare the function name
2

I don't recommend you do this, but if you insist, using eval is an option.
Be extremely careful tho. And keep it far far away from any user input!

<?php
$name = 'sayThis';

$code = <<<PHP
function $name(\$string) {
    echo \$string;
}
PHP;
eval($code);

$name('This is NOT a good idea!');
?>

1 Comment

+1 This looks like it answers the OP's question. It is one of those things to be careful what you ask for.

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.