Skip to content

Instantly share code, notes, and snippets.

@nick-mok
Last active July 8, 2024 12:02
Show Gist options
  • Save nick-mok/5857846 to your computer and use it in GitHub Desktop.
Save nick-mok/5857846 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();
?>
@gwcms
Copy link

gwcms commented May 1, 2017

//shorter version to achieve same result:

class Anonymous_Object
{

protected $methods = array();
public function __construct(array $options)
{
	$this->methods = $options;
}

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);
}

function __get($name)
{
	return $this->methods[$name];
}

}

@furnox
Copy link

furnox commented May 31, 2017

Hi there.

I took your revision and modified it to bind $this to the anonymous methods here. This was coded and tested on PHP 5.5

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