cj333
cj333

Reputation: 2609

PHP string in a function name

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

Answers (4)

linkamp
linkamp

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

DaveRandom
DaveRandom

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

Your Common Sense
Your Common Sense

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.

  1. there should be no functions like my_function_$i() but one function my_function($i)
  2. There should be no enumerated includes as well. What are these php files for?

Upvotes: 8

Blake K Peterson
Blake K Peterson

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

Related Questions