Created
December 2, 2012 16:45
-
-
Save krolow/4189729 to your computer and use it in GitHub Desktop.
PHP Adding method dynamically, meta programming example in PHP 5.3
This file contains hidden or 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 | |
/** | |
* Example in PHP 5.3 | |
*/ | |
class Meta | |
{ | |
private $methods = array(); | |
public function addMethod($methodName, $methodCallable) | |
{ | |
if (!is_callable($methodCallable)) { | |
throw new InvalidArgumentException('Second param must be callable'); | |
} | |
$this->methods[$methodName] = $methodCallable; | |
} | |
public function __call($methodName, array $args) | |
{ | |
if (isset($this->methods[$methodName])) { | |
array_unshift($args, $this); | |
return call_user_func_array($this->methods[$methodName], $args); | |
} | |
throw RunTimeException('There is no method with the given name to call'); | |
} | |
} |
This file contains hidden or 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 | |
/** | |
* Example in PHP 5.3 | |
*/ | |
require 'Meta.php'; | |
$meta = new Meta(); | |
$meta->addMethod('color', function ($self) { | |
$self->name = 'My Name'; | |
return '#00000'; | |
}); | |
echo $meta->color(), PHP_EOL; | |
echo $meta->name, PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment