Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a variable defined in a parent function

Tags:

scope

php

Is there a way to access $foo from within inner()?

function outer()
{
    $foo = "...";

    function inner()
    {
        // print $foo
    }

    inner();
}

outer();
like image 444
Emanuil Rusev Avatar asked Feb 08 '11 20:02

Emanuil Rusev


People also ask

How do you access a variable in a function?

First, declare it outside the function, then use it inside the function. You can't access variables declared inside a function from outside a function. The variable belongs to the function's scope only, not the global scope.

What is block scope in JavaScript?

Block Level Scope: This scope restricts the variable that is declared inside a specific block, from access by the outside of the block. The let & const keyword facilitates the variables to be block scoped.

What is closure method in JavaScript?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.

Why Closures are used in JavaScript?

In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can't get at the data from an outside scope except through the object's privileged methods.


2 Answers

PHP<5.3 does not support closures, so you'd have to either pass $foo to inner() or make $foo global from within both outer() and inner() (BAD).

In PHP 5.3, you can do

function outer()
{
  $foo = "...";
  $inner = function() use ($foo)
  {
    print $foo;
  };
  $inner();
}
outer();
outer();
like image 123
simshaun Avatar answered Oct 20 '22 08:10

simshaun


Or am I missing something more complex you are trying to do?

function outer()
{
    $foo = "...";

    function inner($foo)
    {
        // print $foo
    }

    inner($foo);
}

outer();

edit Ok i think i see what you are trying to do. You can do this with classes using global, but not sure about this particular case

like image 37
Jonathan Avatar answered Oct 20 '22 09:10

Jonathan