Curiosa creación de objetos en PHP

Recuerda mucho a Javascript y frameworks tipo jQuery, para ello utiliza métodos encadenados y un objeto genérico:


// Define a new class
$animal = $class->new()
  ->def('init', function($t, $name) {
    $t->name = $name;
  })
  ->def('speak', function($t) {
    echo "My name is $t->name\n";
  });

// Extend a class
$dog = $animal->extend()
  ->def('speak', function($t) {
    echo "My name is $t->name, I have just met you and I love you, SQUIRREL!\n";
  })
  ->def('bark', function($t) {
    echo "Woof!\n";
  });

Para poder realizar esto se necesita crear la clase Obj:

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

  public function method($name) {
    if (!isset($this->methods[$name]))
      throw new BadMethodCallException();
    return $this->methods[$name];
  }

  public function fn($name, $fn) {
    $this->methods[$name] = $fn;
    return $this;
  }

  public function __call($name, $args) {
    return call_user_func_array(
      $this->method($name),
      array_merge(array($this), $args)
    );
  }
}

// Allow chaining method calls off the constructor..
function Obj($methods=array())
{
return new Obj($methods);
}

PHP Object Oriented Programming Reinvented

Vía / PHPDeveloper.org