Skip to content

Instantly share code, notes, and snippets.

@krolow
Last active October 4, 2019 15:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save krolow/4264062 to your computer and use it in GitHub Desktop.
Save krolow/4264062 to your computer and use it in GitHub Desktop.
PHP Meta Programming PHP 5.4
<?php
trait MetaTrait
{
private $methods = array();
public function addMethod($methodName, $methodCallable)
{
if (!is_callable($methodCallable)) {
throw new InvalidArgumentException('Second param must be callable');
}
$this->methods[$methodName] = Closure::bind($methodCallable, $this, get_class());
}
public function __call($methodName, array $args)
{
if (isset($this->methods[$methodName])) {
return call_user_func_array($this->methods[$methodName], $args);
}
throw new RunTimeException('There is no method with the given name to call');
}
}
<?php
require 'MetaTrait.php';
class HackThursday {
use MetaTrait;
private $dayOfWeek = 'Thursday';
}
$test = new HackThursday();
$test->addMethod('when', function () {
return $this->dayOfWeek;
});
echo $test->when();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment