Skip to content

Instantly share code, notes, and snippets.

@furnox
Forked from nick-mok/AnObj.php
Last active January 2, 2020 19:07
Show Gist options
  • Save furnox/ffe5cffc9dc2c8ee7f7c23e1601a33ed to your computer and use it in GitHub Desktop.
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.
<?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