|
Posted by Jerry Stuckle on 02/24/06 23:42
m.epper@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.
jstucklex@attglobal.net
==================
Navigation:
[Reply to this message]
|