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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With