Reply to Re: Execute code in global scope

Your name:

Reply:


Posted by Jerry Stuckle on 02/24/06 19:44

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?
>

Actually, your English is quite good - better than some native English
speakers!

Your problem is $var is not defined within the function.

Each function has its own variables which normally do not mix with other
functions and the global scope. This is so you don't have to worry
about name collisions in your code.

You can define $var as global by placing

global $var;

BOTH in the global scope and in the function, i.e.

<?php
global $var;
$var="hello world";
function myfunc(){
global $var;
eval("echo $var;");
// The above line can be replaced by a simple eval-less
// echo $var;
}
myfunc();
?>

However globals are pretty much frowned upon because the function is now
tightly tied to the main part of the code - you can't change the name of
the variable in either without changing it in both, for instance.

A better way would be to pass $var as a parameter to the function, i.e.

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

Here the variable is known as $var in the main part of your code, but
$func_var in the function. And additional advantage here is you can
call the function with $myvar, $yourvar, $anothervar, etc. - you aren't
tied to using just $var, which makes it much more flexible and reusable.


--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@attglobal.net
==================

[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

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