-
-
Save furnox/ffe5cffc9dc2c8ee7f7c23e1601a33ed to your computer and use it in GitHub Desktop.
This is a revision of Nick Mokisasian's (https://gist.github.com/nickunderscoremok/5857846) revision of George Mihailov's (https://gist.github.com/Mihailoff/3700483) PHP Anonymous Object Class. I wanted to bind $this to the methods in the anonymous class. Coded and tested on PHP 5.5.
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 | |
class AnObj | |
{ | |
protected $methods = array(); | |
protected $properties = array(); | |
public function __construct(array $options) | |
{ | |
foreach($options as $key => $opt) { | |
//integer, string, float, boolean, array | |
if(is_array($opt) || is_scalar($opt)) { | |
$this->properties[$key] = $opt; | |
unset($options[$key]); | |
} | |
} | |
$this->methods = $options; | |
foreach($this->properties as $k => $value) | |
$this->{$k} = $value; | |
} | |
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"); | |
// let's bind $this to the method | |
$method = $callable->bindTo($this); | |
return call_user_func_array($callable, $arguments); | |
} | |
} | |
$person = new AnObj(array( | |
"name" => "nick", | |
"age" => 23, | |
"friends" => ["frank", "sally", "aaron"], | |
"sayHi" => function() {return "Hello there " . $this->name;} | |
)); | |
echo $person->name . ' - '; | |
echo $person->age . ' - '; | |
print_r($person->friends) . ' - '; | |
echo $person->sayHi(); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment