A software engineer bent on world bovine domination.
I write code at 99designs + Swiftly and on GitHub.

By Dennis Hotson.

Sep 22

PHP Object Oriented Programming Reinvented

I’ve recently been experimenting with some different object orientation ideas in PHP.

It’s tentatively called “PHP Object Oriented Programming Reinvented”. Although it turns out the acronym is kind of unfortunate. I’m still working on that… ;-)

The main idea is that classes aren’t really very special at all, they’re just objects like everything else. They don’t even have names… you give your class a name by giving the variable it’s assigned to a name.

Here’s the most interesting part:


// Define the 'class' class
$class = Obj()
  ->fn('new', function ($class) {
    $newClass = Obj($class->methods)
      ->fn('new', function($class) {
        $obj = Obj($class->imethods);
        $args = func_get_args();
        call_user_func_array(array($obj, 'init'), $args);
        return $obj;
    return $newClass;
  ->fn('def', function ($t, $name, $fn) {
      $t->imethods[$name] = $fn;
      return $t;
  ->fn('extend', function ($t) {
      return clone $t;

// 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";

$jimmy = $animal->new('Jimmy');

$doug = $dog->new('Doug');

.. pretty neat right? Check out the full code here.

There are some interesting implications of this:

  • Classes can be hacked / patched / cloned. Methods can be added to classes at any time
  • Classes can be scoped. They’re not global, unless you want them to be.
  • Classes can be temporary (and garbage collected).

I’m still experimenting with the idea, but I think I’ve come up with something pretty interesting.

As usual, feedback is welcome. Let me know what you think! :-)