Mixing eval() with include/require

From: Date: Thu, 21 Dec 2000 11:29:26 +0000
Subject: Mixing eval() with include/require
Groups: php.general 
Request: Send a blank email to php-general+get-31411@lists.php.net to get a copy of this message
I have several files containing PHP code, any one of which I need to bring into PHP as a function at runtime. An example would probably explain it best: ---test1.inc: <?php print('Test code 1<br>'); ?> ---test2.inc <?php print('Test code 2<br>'); ?> At runtime I have a function which will be passed the function number (1 or 2 here, but I won't know in advance what possible values will be presented). I need to call the code that's in that file several times during a loop (the actual code amounts to many lines, not just the single line example above). What I tried was: ---test.php <?php function Test($id) { $fn = 'testfunc'.$id; eval("function $fn() { include('test$id.inc'); }"); for ($i=0; $i<1000; $i++) $fn(); } ?> To my surprise this almost worked! The problem is with the include itself. Using include the function works, but because it re-reads the include file each time the function is called it is very slow. Using include_once causes the function to only work the first time through the loop. I've tried require/require_once but these seem to make no difference. Is there any way around this? The above is vastly stripped down, of-course, and in doing so hides some of the reasons for it being written this way. For example, the function name needs to be a variable because Test() itself will be called several times, with varying values of $id, so I need to make sure I don't define the same function more than once.

« previous php.general (#31411) next »