Created
September 7, 2016 10:54
-
-
Save frak/8abd6d73b116d4fe31f007f4683e6ab9 to your computer and use it in GitHub Desktop.
Referencing $this in a closure works :S
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Called | |
{ | |
public function doThis($callback) | |
{ | |
$callback('this is not a love song'); | |
} | |
} | |
class Output | |
{ | |
public function write($message) | |
{ | |
echo $message.PHP_EOL; | |
} | |
} | |
class Caller | |
{ | |
private $output; | |
public function __construct() | |
{ | |
$this->output = new Output(); | |
} | |
public function doThat() | |
{ | |
$called = new Called(); | |
$action = function($message) use ($output) { | |
$this->output->write($message); | |
}; | |
$called->doThis($action); | |
} | |
} | |
$caller = new Caller(); | |
$caller->doThat(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment