Skip to content

Instantly share code, notes, and snippets.

@krolow
Created December 2, 2012 16:45
Show Gist options
  • Save krolow/4189729 to your computer and use it in GitHub Desktop.
Save krolow/4189729 to your computer and use it in GitHub Desktop.
PHP Adding method dynamically, meta programming example in PHP 5.3
<?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');
}
}
<?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