Re: Mixing eval() with include/require

From: Date: Thu, 21 Dec 2000 17:19:15 +0000
Subject: Re: Mixing eval() with include/require
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-31445@lists.php.net to get a copy of this message
On Thu, 21 Dec 2000, Mark Rogers wrote: > 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. > Try: <?php function Test($id) { for ($i=0; $i<1000; ++$i) include("test$id.inc"); }; ?> include()s can be dynamic that way; AFAIK require()s can't. -- Ignacio Vazquez-Abrams <ignacio@openservices.net>

« previous php.general (#31445) next »