How to access a global object inside a method closure

Currently, I have a dependency injection module that allows me to create factory objects:

class DiModule { private $Callbacks; public function set( $foo, $bar ) { $this->Callbacks[$foo] = $bar; } public function get( $foo ) { return $this->Callbacks[$foo]; } } 

Then I have an event object that stores the closure of the method and a session that raises the event.

 class Event { private $Sesh; private $Method; public function set( $sesh = array(), $method ) { $this->Sesh = $sesh; $this->Method = $method; } public function get( ) { return [$this->Sesh,$this->Method]; } } 

Then I have a listener object that searches for established sessions and fires the event associated with that object.

 class Listener { private $Sesh; public function setSesh( $foo ) { $this->Sesh = $foo; } private $Event; public function set( $foo, Event $event ) { $this->Event[$foo] = $event; } public function dispatch( $foo ) { $state = true; if(isset($this->Event[$foo])) { foreach($this->Event[$foo]->get()[0] as $sesh) { if(!isset($this->Sesh[$sesh]) || empty($this->Sesh[$sesh])) { $state = false; } } } return ($state) ? [true, $this->Event[$foo]->get()[1]()] : [false, "Event was not triggered."]; } } 

This is an example of accomplishment.

 $di = new DiModule(); $di->set('L', new Listener()); $di->set('E', new Event()); $di->get('E')->set(['misc'], function () { global $di; return $di; }); $di->get('L')->setSesh(array('misc' => 'active')); // not actual sessions yet $di->get('L')->set('example', $di->get('E')); var_dump($di->get('L')->dispatch('example')); 

The problem is that when I try to access my global $di inside a closure, I have repeatedly searched for this problem but cannot find a solution.

+5
source share
2 answers

You need to use the use keyword to access an external variable from the closure.

So this is:

 $di->get('E')->set(['misc'], function () { global $di; return $di; }); 

It should be written like this:

 $di->get('E')->set(['misc'], function () use ($di) { return $di; }); 
+4
source

The set() and get() methods of your DiModule class have inappropriate names / implementations.

The code you entered has the following methods:

 function get($foo, $bar) { /* ... */ } function set($foo) { /* ... */ } 

Most likely it will be:

 function get($foo) { /* ... */ } function set($foo, $bar) { /* ... */ } 

To make these errors less likely, give arguments to meaningful names (for example, $key and $value ) instead of the common $foo and $bar . Then it would be easier to notice.

+2
source

Source: https://habr.com/ru/post/1257518/


All Articles