Skip to content

Instantly share code, notes, and snippets.

@frak
Created September 7, 2016 10:54
Show Gist options
  • Save frak/8abd6d73b116d4fe31f007f4683e6ab9 to your computer and use it in GitHub Desktop.
Save frak/8abd6d73b116d4fe31f007f4683e6ab9 to your computer and use it in GitHub Desktop.
Referencing $this in a closure works :S
<?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