Skip to content

Instantly share code, notes, and snippets.

@igorw
Created July 29, 2011 20:15
Show Gist options
  • Save igorw/1114629 to your computer and use it in GitHub Desktop.
Save igorw/1114629 to your computer and use it in GitHub Desktop.
playing with PHP 5.4
<?php
class Container extends ArrayObject
{
}
trait ContainerAware
{
private $container;
public function setContainer(Container $container)
{
$this->container = $container;
}
public function get($name)
{
return $this->container[$name];
}
}
class Guitar
{
public function rock()
{
return 'CRAZY SHIT GUITAR SOLO!';
}
}
class Rockstar
{
use ContainerAware;
public function getSongs()
{
return [
'Smoke on the water',
'Other shizzle',
];
}
public function getOneSongLater()
{
return function ($i) {
return $this->getSongs()[$i];
};
}
public function rockTheGuitar()
{
return $this->get('guitar')->rock();
}
}
$star = new Rockstar();
var_dump($star->getSongs()[0]);
$f = $star->getOneSongLater();
var_dump($f(1));
$container = new Container();
$container['guitar'] = new Guitar();
$star->setContainer($container);
var_dump($star->rockTheGuitar());
@julesbou
Copy link

Did you omit the $i argument for Rockstar::getOneSongLater() ?

@igorw
Copy link
Author

igorw commented Jul 30, 2011

It's an argument to the closure, allowing you to specify it later - e.g. at closure call time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment