Mehdi
Mehdi

Reputation: 181

php variable scope in functions?

How can I access to a variable within a function which defined in another function?

For example:

<?php
    function a() {
        $fruit = "apple";

        function b(){
            $country="USA";
            // How can I here access to $fruit
        }

        // And how can I here access to $country  
    }
?>

Upvotes: 0

Views: 68

Answers (2)

Matas Lesinskas
Matas Lesinskas

Reputation: 444

u can use global word. Try it and tell me if it works.

<?php
        function a() {
            $fruit = "apple";

            $country=b();

            // And how can I here access to $country  
        }
            function b(){
    global $fruit;
                $country="USA";
                // How can I here access to $fruit
                return $country;
            }
    ?>

,but u should do like that

<?php
        function a() {
            $fruit = "apple";

            $country=b($fruit);

            // And how can I here access to $country  
        }
            function b($fruit){
                $country="USA";
                // How can I here access to $fruit
                return $country;
            }
    ?>

Upvotes: 0

Evert
Evert

Reputation: 99505

What you're doing is a pretty bad practice, because PHP's functions can't be nested like javascript in this manner. In your example a and b are both just global functions, and you'll get an error if you try to call a twice.

What I suspect you want, is this syntax:

function a() {
    $fruit = "apple";
    $country = null;

    $b = function() use ($fruit, &$country) {
        $country="USA";
        // How can I here access to $fruit
    };

    // And how can I here access to $country  
}

Of course, you will need to call $b() inside $a().

Upvotes: 1

Related Questions