Page 1 of 1

More fun with eval()

Posted: Fri Sep 06, 2002 11:03 am
by jschoneb
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!

Posted: Fri Sep 06, 2002 11:10 am
by Takuma
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(); 
?>

Posted: Fri Sep 06, 2002 12:43 pm
by jschoneb
Done that, actually. It just echoes nothing, it isn't getting the variable at all.

Thanks for the reply though!

Posted: Fri Sep 06, 2002 3:06 pm
by jschoneb
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);

Posted: Fri Sep 06, 2002 5:10 pm
by sugarmen
I try out the code and i've no problems !
The prodcedure echoes 'hey' !!!

Posted: Fri Sep 06, 2002 6:07 pm
by jschoneb
Interesting!

I'm not sure if I consider that good news or bad news.

It would seem to restore order in the universe, on the one hand, and yet it would also seem to leave me (and/or my server) out in the cold while the rest of the universe parties...

Thanks for the feedback, in any case!