开发者

Declare a Function in PHP Using a String?

Invalid code:

$functionName = 'sayThis';

function $functionName($string) 开发者_如何转开发{
    echo $string;
}

Can I do anything like this?


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


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!');
?>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜