Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variable from function inside of nested function [duplicate]

In PHP, you have to use the global keyword in order to access a variable from the global scope when inside of a function. However, how can you access a variable within the scope of a parent function?

In the example:

function foo() {
    $content = 'foobar';

    function bar() {
        echo $content; // echos nothing
    }
}

How can I access the $content variable?

like image 803
Mystical Avatar asked Sep 10 '25 23:09

Mystical


1 Answers

You have two options:

  1. Give $content as a parameter

    function foo() {
        $content = 'foobar';
    
        function bar($content) {
            echo $content . '1'; // 'foobar1'
        }
    
        bar();
    }
    
    foo();
    
  2. Use closures (PHP Manual) (PHP 5.3.0+)

    Please note that the function declaration is a bit different compared to the 'conventional way' of declaring functions.

    function foo() {
        $content = 'foobar';
    
        $bar = function() use ($content) {
            echo $content . '1';
        };  // <-- As it's an assignment, end with a ';'
    
        $bar();
    }
    
    foo();  // 'foobar1'
    
like image 110
Kerwin Sneijders Avatar answered Sep 12 '25 14:09

Kerwin Sneijders