chicane
chicane

Reputation: 2071

function within function in PHP

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();

}

Upvotes: 1

Views: 273

Answers (3)

wallyk
wallyk

Reputation: 57764

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 ~]$

Upvotes: 3

Gal
Gal

Reputation: 23662

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.

Upvotes: 0

malonso
malonso

Reputation: 2295

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

Upvotes: 0

Related Questions