Skip to content

Instantly share code, notes, and snippets.

@leo4all
Created October 10, 2018 19:29
Show Gist options
  • Save leo4all/a3669b9fd0be2edfc92b77191a3ed900 to your computer and use it in GitHub Desktop.
Save leo4all/a3669b9fd0be2edfc92b77191a3ed900 to your computer and use it in GitHub Desktop.

Revisions

  1. leo4all created this gist Oct 10, 2018.
    45 changes: 45 additions & 0 deletions MetaTrait.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    <?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 RunTimeException('There is no method with the given name to call');
    }

    }
    ?>

    test.php
    <?php
    require 'MetaTrait.php';

    class HackThursday {
    use MetaTrait;

    private $dayOfWeek = 'Thursday';

    }

    $test = new HackThursday();
    $test->addMethod('when', function () {
    return $this->dayOfWeek;
    });

    echo $test->when();

    ?>