Created
June 28, 2011 03:41
-
-
Save nfeldman/1050444 to your computer and use it in GitHub Desktop.
abusing magic methods to create an object just JS-esque enough to make you nostalgic, if you squint
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 | |
/** | |
* Objects of this class are superficially similar to JavaScript objects | |
* in that you can dynamically add and overwrite both properties and methods | |
* the resemblance is not very strong, though. | |
*/ | |
// Note, there are a few ways to pass functions around | |
// in arrays is one | |
// $F = array(); | |
// | |
// $F['hello'] = function ($say = 'world!') { | |
// print('Hello, ' . $say . '<br>'); | |
// }; | |
// which you can cast to object, but the hello property isn't a method | |
// | |
// $G = (object) $F; | |
// | |
// echo method_exists($G, 'hello') ? 'true' : 'false'; | |
// echo '<pre>' . print_r(get_object_vars($G), 1) . '</pre>'; | |
// | |
// but is still callable if you're willing to get ugly: | |
// call_user_func($G->hello); | |
// Alternatively, you can abuse the magic methods __set, __get, and __call | |
class DynamicObject { | |
protected $methods = array(); | |
protected $properties = array(); | |
public function __set($name, $value) { | |
// overwrite existing properties and methods without warning, js would | |
return is_callable($value) ? $this->methods[$name] = $value : $this->properties[$name] = $value; | |
} | |
public function __get($prop) { | |
return $this->properties[$prop] ? : false; | |
} | |
public function __call($name, $args) { | |
return $this->methods[$name](implode(',', $args)); | |
} | |
} | |
// pretend we want a utility object to pass around | |
$utils = new DynamicObject(); | |
$utils->hello = function ($hello = 'world!') { | |
print('Hello, ' . $hello . '<br>'); | |
}; | |
$utils->prefix = 'Mr.'; | |
$utils->hello($utils->prefix . ' sailor!'); // Hello, Mr. sailor! | |
echo $utils->prefix; // Mr. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment