Skip to content

Instantly share code, notes, and snippets.

@dhotson
Created December 6, 2011 12:02
Show Gist options
  • Save dhotson/1437956 to your computer and use it in GitHub Desktop.
Save dhotson/1437956 to your computer and use it in GitHub Desktop.
PHP Object Oriented Programming Reinvented (for PHP 5.4)
<?php
// Define the 'class' class
$class = (new Obj)
->fn('new', function() {
$newClass = (new Obj($this->methods))
->fn('new', function() {
$obj = new Obj($this->imethods);
call_user_func_array(array($obj, 'init'), func_get_args());
return $obj;
});
return $newClass;
})
->fn('def', function($name, $fn) {
$this->imethods[$name] = $fn->bindTo($this);
return $this;
})
->fn('extend', function() {
return clone $this;
});
// Define a new class
$animal = $class->new()
->def('init', function($name) {
$this->name = $name;
})
->def('speak', function() {
echo "My name is $this->name\n";
});
// Extend a class
$dog = $animal->extend()
->def('speak', function() {
echo "My name is $this->name, I have just met you and I love you, SQUIRREL!\n";
})
->def('bark', function() {
echo "Woof!\n";
});
$jimmy = $animal->new('Jimmy');
$jimmy->speak();
$doug = $dog->new('Doug');
$doug->speak();
$doug->bark();
// ---- The guts...
class Obj
{
public function __construct($methods=array())
{
$this->methods = array_map(function($fn) {
return $fn->bindTo($this);
}, $methods);
}
public function method($name)
{
if (!isset($this->methods[$name]))
throw new BadMethodCallException($name);
return $this->methods[$name];
}
public function fn($name, $fn)
{
$this->methods[$name] = $fn->bindTo($this);
return $this;
}
public function __call($name, $args)
{
return call_user_func_array(
$this->method($name),
$args
);
}
}
@philsturgeon
Copy link

The only thing I liked about any of this was the squirrel. Please don't do this.

https://wiki.php.net/rfc/anonymous_classes

Use them if they pass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment