0

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  
    }
?>
11
  • 1
    You can pass $fruit as an argument to your b()-function. You then return $country from your b() function and use the response. Commented Sep 10, 2018 at 8:16
  • or you can call function inside function:- eval.in/1055852 Commented Sep 10, 2018 at 8:18
  • @MagnusEriksson yeah, so there is no other way to do that ? Commented Sep 10, 2018 at 8:19
  • Sure. There are plenty of creative ways of doing it, but the question is why? Commented Sep 10, 2018 at 8:21
  • you can call a method b($fruit), pass the fruit in this method or either you can declare globally that variable for accessing the value.this is not a good you need to make an another function outside that a() function. Commented Sep 10, 2018 at 8:25

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Using global is not good practice. Also $country is still not accessible in the function a
why are u defineing functions inside functions :D do like that :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.