Reply to Re: Execute code in global scope

Your name:

Reply:


Posted by Anonymous on 02/24/06 19:15

m.epper@gmail.com wrote:
>
> Hi to everybody.
>
> First of all sorry for my english, I'm italian.
>
> How can I execute a portion of code, in a function, into the global
> scope?
>
> Example:
>
> <?php
> $var="hello world";
> function myfunc(){
> eval("echo $var;");
> }
> myfunc();
> ?>
>
> I need to see "hello world".
>
> Is there any solution?

Sure, that's actually really easy and could have been solved by yourself
within less than 2 minutes if you read the error log of your browser and
the PHP manual.

Error 1: Within the function you are accessing a local version of $var,
which is undefined. You have to tell PHP to use the global $var within
the function.

Error 2: With error 1 out of the way your eval statement will evaluate
to

eval("echo hello world;");

which will not work, because echo needs quotes around the string it
should output. Since you are already within double quotes you have to
use escaped double quotes (\"). The line should look like this:

eval("echo \"$var\";");

This program works exactly as you wish:

<?php
$var="hello world";
function myfunc(){
global $var;
eval("echo \"$var\";");
}
myfunc();
?>

[Back to original 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

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