Skip to content

Instantly share code, notes, and snippets.

@dskarbek
Forked from Mihailoff/AnObj.php
Last active February 15, 2016 19:41
Show Gist options
  • Save dskarbek/372b9cb2a3d77981f3d7 to your computer and use it in GitHub Desktop.
Save dskarbek/372b9cb2a3d77981f3d7 to your computer and use it in GitHub Desktop.
PHP Anonymous Object
<?php
/**
* PHP Anonymous Object
* Dan Skarbek's extension to Mihailoff's solution that makes it easier to
* create properties along with methods in the anonymous object.
*/
class AnObj
{
public function __construct(array $options)
{
foreach($options as $key => $opt)
{
$this->$key = $opt;
}
}
public function __call($name, $arguments)
{
if (! isset($this->$name) || ! is_callable($this->$name))
{
throw new BadMethodCallException("Method {$name} does not exist");
}
return call_user_func_array($this->$name, $arguments);
}
}
// USAGE
// define by passing in constructor
$anonim_obj = new AnObj(array(
"prop" => "property \n",
"foo" => function() { echo "foo \n"; },
"bar" => function($bar) { echo $bar; }
));
$anonim_obj->foo();
$anonim_obj->bar("hello, world \n");
// define at runtime
$anonim_obj->zoo = function() { echo "zoo \n"; };
$anonim_obj->zoo();
// mimic self
$anonim_obj->propMethod = function() use($anonim_obj) { echo $anonim_obj->prop; };
$anonim_obj->propMethod();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment