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
  • 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();
?>
@dskarbek
Copy link

Perhaps it would be cleaner to simply say if (! is_callable($opt)) { /* treat it as a property */ }. Then in your __call() method there is no chance of it not being callable because everything else was treated as a property.

@dskarbek
Copy link

Note that the properties member array is unnecessary, you can just directly do $this->$key = $opt; in the first foreach loop.

In fact, perhaps the methods member array is unneeded also, you could add those to the class via the same code and then in the call method just always look for isset($this->$name).

@dskarbek
Copy link

BTW, if you want to make a method that needs to use the "$this" pointer you can, but you have to add that method to the class after the initial construction. So, in your example, after $person is declared you could declare:
$person->getFriend = function($id) use($person) { return $person->friends[$id]; };

@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