Reputation: 2609
How to put PHP string in a function name?
for ($i=1;$i<10;$i++) {
function my_function_$i() {
//Parse error: syntax error, unexpected T_VARIABLE, expecting '('
include($i.'.php');
}
}
UPDATE:
OK. closed this question, I shall study for more.
Upvotes: 0
Views: 156
Reputation: 215
Maybe you can use eval for do like this:
for ($i=1;$i<10;$i++) {
eval('function myfunc_'.$i.'(){echo '.$i.';}');
}
myfunc_5();
//Output
//5
Upvotes: -3
Reputation: 88647
Firstly, this is a horrible thing to do. Consider using closures, or create_function()
, or passing $i
as an argument.
Secondly - the only way I can think of to do this (but for Christ's sake, don't) is with eval()
:
for ($i = 1; $i < 10; $i++) {
eval("function my_function_$i() {
include('$i.php');
}");
}
Upvotes: 0
Reputation: 157828
there is something utterly wrong with your architecture if you come to a question like this.
it seems you do not understand what functions are for.
my_function_$i()
but one function my_function($i)
Upvotes: 8
Reputation: 481
Check this out - maybe what you're looking for
http://php.net/manual/en/function.create-function.php
from that page:
<?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
?>
Upvotes: 1