Skip to content

Instantly share code, notes, and snippets.

@nick-mok
Forked from Mihailoff/AnObj.php
Last active May 31, 2017 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nick-mok/5858099 to your computer and use it in GitHub Desktop.
Save nick-mok/5858099 to your computer and use it in GitHub Desktop.
This is a revision of George Mihailhoff's PHP Anonymous Object Class. I stumbled upon this class as I was looking for a way to attach functions to properties in a stdClass. This is not directly possible as there is no __call function inbuilt. And I found this code on a stackoverflow post that George had answered. However the implementation didn'…
<?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");
return call_user_func_array($callable, $arguments);
}
}
$person = new AnObj(array(
"name" => "nick",
"age" => 23,
"friends" => ["frank", "sally", "aaron"],
"sayHi" => function() {return "Hello there";}
));
echo $person->name . ' - ';
echo $person->age . ' - ';
print_r($person->friends) . ' - ';
echo $person->sayHi();
?>
@furnox
Copy link

furnox commented May 31, 2017

No you don't. You just need to bind $this to the function. I modified this gist to do this here.

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