Skip to content

Instantly share code, notes, and snippets.

@nyamsprod
Last active December 28, 2015 10:09
Show Gist options
  • Save nyamsprod/7484448 to your computer and use it in GitHub Desktop.
Save nyamsprod/7484448 to your computer and use it in GitHub Desktop.
How to use anonymous function to create new object
<?php
class Toto
{
private $foo;
public function __construct($foo)
{
$this->setFoo($foo);
}
public function getFoo()
{
return $this->foo;
}
public function setFoo($foo)
{
$this->foo = $foo;
return $this;
}
}
class Collection
{
private $data = [];
public function set($key, $value)
{
$this->data[$key] = $value;
}
public function get($key)
{
return $this->data[$key];
}
}
echo '<pre>', PHP_EOL;
//BAD USE ...
$collection = new Collection;
$collection->set('foo', new Toto('bar'));
echo $collection->get('foo')->getFoo(), PHP_EOL; //bar;
$foo = $collection->get('foo');
$foo->setFoo('baz');
echo $collection->get('foo')->getFoo(), PHP_EOL; //baz;
//IMPROVE USE THANKS TO MAGIC __invoke
$collection->set('toto', function () {
return new Toto('bar');
});
echo $collection->get('toto')->__invoke()->getFoo(), PHP_EOL; //bar;
$toto = $collection->get('toto')->__invoke();
$toto->setFoo('baz');
echo $toto->getFoo(), PHP_EOL; //baz
echo $collection->get('toto')->__invoke()->getFoo(), PHP_EOL; //bar;
//coool tu instancie 1 nouvelle object à chaque fois mais tu dois des fois
// explicitement utiliser __invoke;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment