Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to create new scope in php without creating a new function?

Tags:

scope

php

In java we can create a new scope like this:

    {
        //create new scope
        {
    //        create another new scope
        }
    }

But can I do this in PHP too to create new nested scope?

like image 378
sohan nohemy Avatar asked Oct 21 '25 09:10

sohan nohemy


1 Answers

PHP creates scope for a whole function (or required file, as mentioned by others in comments). You can simulate nested scope by creating nested anonymous function like this:

function scope_outer() {

    $outer_a = 'oa';
    $outer_b = 'ob';
    $inner_a = 'xxx'; // just to check if the nested function overwrites this

    // define anonymous function to simulate nested scope and run it right away
    (function() use($outer_b) {

        $inner_a = 'ia';

        var_dump($outer_a); // error, variable not visible in this scope
        var_dump($outer_b); // "ob"
        var_dump($inner_a); // "ia"

    })();

    var_dump($inner_a); // "xxx" => nested "scope" did *not* overwrite this variable
}

scope_outer();

The fiddle to play with: http://sandbox.onlinephpfunctions.com/code/7b4449fe47cc48aefa61294883400a42659de4c6

like image 120
Roman Hocke Avatar answered Oct 23 '25 23:10

Roman Hocke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!