You are here: Re: Execute code in global scope « PHP Programming Language « IT news, forums, messages
Re: Execute code in global scope

Posted by Chung Leong on 02/25/06 03:32

m.epper@gmail.com wrote:
> I've some restrictions: I can't change $code and I can't put eval
> outside functions or directly into the main script.
> So my question is: "Is there any way to evaluate some php code from a
> function, but into the global scope?"

No, it is not possible. The Zend engine isn't flexible like that. It
can only reach the global scope after popping all function scopes. You
can sort of mimick global scope with something like this:

function bobo_the_clown($code) {
// map in global variables
$global_vars = array_keys($GLOBALS);
foreach($global_vars as $var) {
if($var !== 'GLOBALS') {
$$var =& $GLOBALS[$var];
}
}
eval($code);
unset($var);
unset($code);

// map new local variables to global scope
$local_vars = array_keys(get_defined_vars());
$new_global_vars = array_diff($local_vars, $global_vars);
foreach($new_global_vars as $var) {
if($var !== 'global_vars') {
$GLOBALS[$var] =& $$var;
}
}
}

But in your case this won't work, as the variables declared in $code
could be used prior to them being mapped to the global variable-space.
One thing you can try is to look for global declarations within $code,
then mapped those to $GLOBALS before eval(). The syntax is fairly
regular so it should work.

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация