tags:

views:

109

answers:

3

Hello,

Im having trouble getting a function within a function working, do you think what I have below is done rigth? Im not getting the expected results, if you could shed some light on functions within functions i would appriciete it.

thanks

function test1 ()

{

    global x;

    $x=123;

    function test2()
    {
    echo $x;
    }

    test2();

}
A: 

Can't you just include it as another function outside the first function (test1)? I'm having trouble picturing a use-case for this.

malonso
A: 

You're not calling the function test2 so there's no reason for it to echo $x.

besides, you should construct the function outside, there's no added value in this case.

sombe
+3  A: 

It works, but the scope of test2() is limited. For example, this works:

[wally@zf ~]$ cat y.php
<?php
function test1 ()
{
        global $x;
        $x=123;

        function test2()
        {
                global $x;
                echo $x;
        }

        test2();
}

test1();
?>
[wally@zf ~]$ php -f y.php
123[wally@zf ~]$
wallyk
wallyk thank you for the insight, this indeed works now. can you explain why you require x to be redeclared once again as a global in the second function?
chicane
It's so that `$x` can be seen outside the respective functions. If `$x=123` were set outside `test1()`, there would be no need for `test1()` to have `global $x`.
wallyk