1

I just simply want to create a function name with a string value.

Something like this:

$ns = 'test';
function $ns.'_this'(){}
test_this();

It of course throws an error.

I've tried with:

function {$ns}.'_this'
function {$ns.'_this'}

but no luck.

Any thoughts?

5 Answers 5

4

You can use create_function to create a function from provided string.

Example (php.net)

<?php
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo "New anonymous function: $newfunc\n";
echo $newfunc(2, M_E) . "\n";
// outputs
// New anonymous function: lambda_1
// ln(2) + ln(2.718281828459) = 1.6931471805599
?>
Sign up to request clarification or add additional context in comments.

2 Comments

Right, I looked at that. I would still like to be able to call the function in the traditional manner, which this doesn't allow for.
^create_function() removed in PHP8+
2

This is not possible. If all you want to do is, to prefix all functions with some common string, maybe you want to use namespaces?

namespace foo {
    function bar() {}
    function rab() {}
    function abr() {}
}
// access from global namespace is as follows:
namespace {
    foo\bar(); foo\rab(); foo\abr();
}

1 Comment

ehhh, I had already been down that road with namespaces. I tell you, php namespaces are terrible. Anyways, I guess that's what I wanted to know was that it CANNOT be done.
2

file with function (somefile.php)

function outputFunctionCode($function_name)
{?>
    function <?php echo $function_name ?>()
    {
    //your code
    }
<?php }

file with code which "declares" the function:

ob_start();
include("somefile.php");
outputFunctionCode("myDynamicFunction");
$contents = ob_get_contents();
ob_end_clean();
$file = fopen("somefile2.php", "w");
fwrite($file,$contents);
fclose($file);
include("somefile2.php");

It is ugly, but then again, it is an extremely bad idea to declare functions with dynamic names.

1 Comment

Agreed, ugly as can be, but it does do what the OP asked
1

using "eval" is not a good practice, but that may serve the purpose similar to your requirements sometimes.

   <?php

 $ns = 'test';
 $funcName = $ns.'_this';
    eval("function $funcName(){ echo 1;}");
    test_this();

?>

Comments

0

Is this what you are looking for?

<?php

function foo($a) {   print 'foo called'.$a; }

$myfunctionNameStr = 'foo';

$myfunctionNameStr(2);

?>

Cause i don't think that you can dynamically construct a function declaration. You can decide at 'runtime' the value of the $myfunctionNameStr though.

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.