Accessing outer variable in PHP 7 anonymous class

http://php.net/manual/en/language.variables.scope.php

There are some instructions in the php variable scope documentation.

This script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

In php, the scope that a method inside a class can access is restricted to the inside of the entire class and cannot be accessed up to other scopes. So I think that the effect you want is not implemented in php, at least until the PHP GROUP decides to change the default behavior of PHP.

Of course, you can still use it by declaring variables as global.


The unique way to access outside variable in this case is use $ _GLOBAL (I don't recommend). If you do not want to use constructor or setter method, my suggestion is to use a STATIC variable inside the anonymous class and set the value after the attribuition to the variable that contains the instance of anonymous class (Its not possible to define the static value before, because the class is anonymous..). Doing this, you have a better control and a static variable, but in certain way this is not very usual, every time when you create a new anonymous class the instance and it values belongs to the VARIABLE that receives the "new object", maybe is better for you to create a real class.. But follow a example with a static value and a anonymous class:

$i = new class {

    public static $foo;
};

var_dump($i::$foo); //No value

$i::$foo = "Some value";

var_dump($i::$foo); //Has value

another solution could be

$outer = 'something';

$instance = new class($outer) {

    private $outer;

    public function __construct($outer) {
        $this->outer = $outer
    }

    public function testing() {
        var_dump($this->outer); 
    }
};

Tags:

Php