Skip to content

Instantly share code, notes, and snippets.

@Mihailoff
Created September 11, 2012 18:17
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save Mihailoff/3700483 to your computer and use it in GitHub Desktop.
Save Mihailoff/3700483 to your computer and use it in GitHub Desktop.
PHP Anonymous Object
<?php
/**
* PHP Anonymous Object
*/
class AnObj
{
protected $methods = array();
public function __construct(array $options)
{
$this->methods = $options;
}
public function __call($name, $arguments)
{
$callable = null;
if (array_key_exists($name, $this->methods))
$callable = $this->methods[$name];
elseif(isset($this->$name))
$callable = $this->$name;
if (!is_callable($callable))
throw new BadMethodCallException("Method {$name} does not exists");
return call_user_func_array($callable, $arguments);
}
}
// USAGE
// define by passing in constructor
$anonim_obj = new AnObj(array(
"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->prop = "property \n";
$anonim_obj->propMethod = function() use($anonim_obj) { echo $anonim_obj->prop; };
$anonim_obj->propMethod();
@nick-mok
Copy link

Thanks a tonne for this! I modified it so you can make properties whilst you initialize a new instance. Check it out:
https://gist.github.com/nickunderscoremok/5857846

I also forked it.

It was fun to learn and work with your code sir! :)

@Mihailoff
Copy link
Author

Good to know that this is helpful for someone!

@kielsoft
Copy link

Awesome, that really solved it for me.

@angeli
Copy link

angeli commented Apr 21, 2016

Thanks from me as well, helped me a lot with testing stuff 👍

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