After some initial trouble with the basics of using eval() to import usable PHP from a database, I have been able to make a bunch of things work. However, I still find that it seems mysteriously capricious at times, even in very simple examples.
Let me share an actual, simple test that failed.
First of all, the master file does a mysql_fetch_array and then has a line like this:
$str = eval("$query_data[content]");
Now let's look at the imported code contained in $query_data[content] in three different permutations of my simple test.
THIS ONE WORKS FINE:
//////////////////
function hey() {
echo "hey";
}
hey();
///////////////////
THIS ONE ALSO WORKS FINE:
//////////////////
function hey() {
echo "hey";
}
$signal = "yes";
if ($signal == "yes") hey();
else echo "whoa";
////////////////////
So both of those echo the word "hey". Very simple, very obvious, very straightforward. Now we get to the fun part. The following example is very nearly as simple as the others, but it doesn't work:
THIS DOESN'T WORK:
//////////////////////
function hey() {
echo "hey";
}
$signal = "yes";
function controller(){
global $signal;
if ($signal == "yes") hey();
else echo "whoa";
}
controller();
////////////////////////
This one echoes "whoa". It isn't recognizing the variable "$signal" even though it has been declared global.
WHY???????????
thanks for any help!
More fun with eval()
Moderator: General Moderators
Try echoing the $signal in the function e.g.
Code: Select all
<?php
function hey() {
echo "hey";
}
$signal = "yes";
function controller(){
global $signal;
echo $signal;
if ($signal == "yes") hey();
else echo "whoa";
}
controller();
?>Don't know if it has anything to do with the quote below (from the comments on eval at php.net), but might it? Not sure I completely get what the return() thing is all about, so any further explanations would be welcome.
If you are trying to evaluate code that calls a function to return a value make sure you call eval with
return().
Ex:
$format_handler = "return(handler_format_csv(\$field, \$field_enc, \$field_esc));";
$line = eval($format_handler);
and not:
$format_handler = "handler_format_csv(\$field, \$field_enc, \$field_esc);";
$line = eval($format_handler);