Skip to content

Instantly share code, notes, and snippets.

@Mihailoff
Created September 11, 2012 18:17

Revisions

  1. Mihailoff created this gist Sep 11, 2012.
    48 changes: 48 additions & 0 deletions AnObj.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    <?php

    /**
    * PHP Anonymous Object
    */
    class AnObj
    {
    protected $methods = array();

    public function __construct(array $options)
    {
    $this->methods = $options;
    }

    public function __call($name, $arguments)
    {
    $callable = null;
    if (array_key_exists($name, $this->methods))
    $callable = $this->methods[$name];
    elseif(isset($this->$name))
    $callable = $this->$name;

    if (!is_callable($callable))
    throw new BadMethodCallException("Method {$name} does not exists");

    return call_user_func_array($callable, $arguments);
    }
    }

    // USAGE

    // define by passing in constructor
    $anonim_obj = new AnObj(array(
    "foo" => function() { echo "foo \n"; },
    "bar" => function($bar) { echo $bar; }
    ));

    $anonim_obj->foo();
    $anonim_obj->bar("hello, world \n");

    // define at runtime
    $anonim_obj->zoo = function() { echo "zoo \n"; };
    $anonim_obj->zoo();

    // mimic self
    $anonim_obj->prop = "property \n";
    $anonim_obj->propMethod = function() use($anonim_obj) { echo $anonim_obj->prop; };
    $anonim_obj->propMethod();