473,385 Members | 2,044 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Execute code in global scope

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?

Feb 24 '06 #1
10 3861
m.*****@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();
?>
Feb 24 '06 #2
m.*****@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.
js*******@attglobal.net
==================
Feb 24 '06 #3
Jerry Stuckle wrote:

You can define $var as global by placing

global $var;

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


That is incorrect. You only need to declare the variable global within the
function to get access to it.

--
Tommy
http://design.twobarks.com/
Feb 24 '06 #4
Anonoymous:
1) Read here, my problem is a bit more complicated.
2) I've read the manual

Jerry Stuckle:
Thanks for the tips.

I know about global and I also know that in the example I've written, a
parameter (is better to say argument?) function would have been better.

My problem is a bit more complicated:

The main script is like this:

<?php
function myFunction($code){
eval($code);
}
myFunction($code);
?>

$code is a var which contains php istructions (without <?php and ?>)
from another file.
This code is written to work indipendently and should be something like
this one:

$var="Hello";
function myFunction2(){
global $var;
$var.=" World";
}

myFunction2();
echo $var;

In this case, if the code works alone, the output will be "Hello
World".

The problem is that this code will be run from eval which is inside
another function.
In this case the php engine will parse something like this:

<?php
function myFunction($code){
$var="Hello";
function myFunction2(){
global $var;
$var.=" World";
}

myFunction2();
echo $var;
}
myFunction($code);
?>

Here the output will be only "Hello" because myFunction2 (which should
add " World" to $var) will try to change the value of $var, a global
variable that doesn't exists!.

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

Thank you
(I suppose to have made some errors now, is this true? :D )

Feb 24 '06 #5
m.*****@gmail.com wrote:

The problem is that this code will be run from eval which is inside
another function.
In this case the php engine will parse something like this:

<?php
function myFunction($code){
$var="Hello";
function myFunction2(){
global $var;
$var.=" World";
}

myFunction2();
echo $var;
}
myFunction($code);
?>

Here the output will be only "Hello" because myFunction2 (which should
add " World" to $var) will try to change the value of $var, a global
variable that doesn't exists!.

Your problem here, is that the variable $var isn't in the global scope to
begin with, it's in the scope of the function myFunction, and even though
myFunction2() is created within myFunction(), it does not inherit
myFunction()'s scope or variables.

The only solution that I can think of right now, would be if you both in
myFunction() and in the eval'ed code containing myFunction2() refer to the
variables via the $GLOBALS array instead of directly using the variable
name.

--
Tommy
http://design.twobarks.com/
Feb 24 '06 #6
m.*****@gmail.com wrote:
Anonoymous:
1) Read here, my problem is a bit more complicated.
2) I've read the manual

Jerry Stuckle:
Thanks for the tips.

I know about global and I also know that in the example I've written, a
parameter (is better to say argument?) function would have been better.

My problem is a bit more complicated:

The main script is like this:

<?php
function myFunction($code){
eval($code);
}
myFunction($code);
?>

$code is a var which contains php istructions (without <?php and ?>)
from another file.
This code is written to work indipendently and should be something like
this one:

$var="Hello";
function myFunction2(){
global $var;
$var.=" World";
}

myFunction2();
echo $var;

In this case, if the code works alone, the output will be "Hello
World".

The problem is that this code will be run from eval which is inside
another function.
In this case the php engine will parse something like this:

<?php
function myFunction($code){
$var="Hello";
function myFunction2(){
global $var;
$var.=" World";
}

myFunction2();
echo $var;
}
myFunction($code);
?>

Here the output will be only "Hello" because myFunction2 (which should
add " World" to $var) will try to change the value of $var, a global
variable that doesn't exists!.

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

Thank you
(I suppose to have made some errors now, is this true? :D )

Ok, in this case your problem is $var is not global in $myFunction -
it's only local there. You need to declare it global there, also.

And BTW - you can change values in a parameter function if you pass by
reference, i.e.

<?php
function myFunction(&$code){
$var="Hello";
function myFunction2(&$var2){
$var2.=" World";
}

myFunction2($var);
echo $var;
}
myFunction($code);
?>

$code is passed by reference to myFunction (as $var), then by reference
to myFunction2 (as $var2). When it's changed in myFunction2, both $var
and $code are changed.

P.S. Please quote relevant portions of the messages you're responding
to. Not everyone has the previous message available. Thanks.
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
js*******@attglobal.net
==================
Feb 24 '06 #7

Jerry Stuckle ha scritto:
P.S. Please quote relevant portions of the messages you're responding
to. Not everyone has the previous message available. Thanks.


I will do it ;)

Thank you very much. The only solution seem that I've to change $code
content. I cannot.
So I'll try to think other solutions...

Thanks again ;)

Feb 24 '06 #8
m.*****@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.

Feb 25 '06 #9
Chung Leong wrote:

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];
}
}


extract($GLOBALS); may seem like a better choice.
I did think about suggesting that, but though that it would make the
script to inefficient to be usefull.
--
Tommy Gildseth
http://design.twobarks.com/
Feb 25 '06 #10
Tommy Gildseth wrote:
extract($GLOBALS); may seem like a better choice.
I did think about suggesting that, but though that it would make the
script to inefficient to be usefull.


extract() creates copies of the global variables. If a change occurs,
it won't be reflected in the actual global variable.

Feb 25 '06 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Robert North | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I've just started programming JS, and one question keeps nagging me: I can insert a <script> element anywhere in HTML, and when it's executed...
5
by: j | last post by:
Anyone here feel that "global variables" is misleading for variables whose scope is file scope? "global" seems to imply global visibility, while this isn't true for variables whose scope is file...
3
by: Zhigang Cui | last post by:
Hi, When I saw 'global static', the first response was there was no such term. But I realized it's an idiom later. When we learn C language, when we study C standard, when we study compiler, we...
2
by: Estella | last post by:
Hello, I wrote a function called eat_path() to split a string into components e.g. /a/b/c ==> namePtr = a,namePtr = a, namePtr = c // Global variable char *namePtr = {0}; int n; /*number of...
3
by: Bas Wassink | last post by:
Hello there, I'm having trouble understanding a warning produced by 'splint', a code-checker. The warning produced is: keywords.c: (in function keyw_get_string) keywords.c:60:31: Released...
5
by: george r smith | last post by:
In the MSDN documentation there is a reference to "the global scope". For example "You can declare types directly in the global scope." I have search extensively and can not find a definition of...
3
by: User1014 | last post by:
A global variable is really just a property of the "Global Object", so what does that make a function defined in the global context? A method of the Global Object? ...
11
by: Sylvia A. | last post by:
How can I define global classes in web application ? Classes can be set to session variables ? Thanks
112
by: istillshine | last post by:
When I control if I print messages, I usually use a global variable "int silent". When I set "-silent" flag in my command line parameters, I set silent = 1 in my main.c. I have many functions...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.