Last active
July 8, 2024 12:02
-
-
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'…
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"); | |
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(); | |
?> |
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
//shorter version to achieve same result:
class Anonymous_Object
{
}