开发者

php create function from string value

I just simply want to create a function name with a stri开发者_开发百科ng 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?


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


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();
}


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.


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();

?>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜