-
-
Save dskarbek/372b9cb2a3d77981f3d7 to your computer and use it in GitHub Desktop.
PHP Anonymous Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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