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:

<?php // 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 ( ) ; array_shift ( $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

" ; } ) ; // 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 !

" ; } ) - > def ( ' bark ' , function ( $t ) { echo " Woof !

" ; } ) ; $jimmy = $animal ->new ( ' Jimmy ' ) ; $jimmy ->speak ( ) ; $doug = $dog ->new ( ' Doug ' ) ; $doug ->speak ( ) ; $doug ->bark ( ) ;

.. 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! :-)