-
-
Save rhowardiv/613443 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// You should make this something that is sensible for your application | |
namespace gist; | |
/** | |
* You can't set functions as callable properties on a normal generic | |
* object. You can on instances of this class. | |
* | |
* You can't use "$this," however, so the function will always receive a | |
* reference to "$this" as the first argument. | |
* | |
* It may not be the wisest thing to use the name StdClass here, but that's what I did. | |
*/ | |
class StdClass | |
{ | |
/** | |
* This is just here as a convenience, since with a real class you lose | |
* the ability to instantiate via (object)array('key' => <value>) | |
*/ | |
function __construct(array $properties=array()) | |
{ | |
foreach ($properties as $k => $v) | |
{ | |
$this->$k = $v; | |
} | |
} | |
function __call($name, $args) | |
{ | |
return call_user_func_array($this->$name, array_merge(array($this), $args)); | |
} | |
} | |
// Allow chaining method calls off the constructor.. | |
function StdClass(array $properties=array()) | |
{ | |
return new StdClass($properties); | |
} | |
// Define the 'class' class | |
$class = StdClass(array( | |
'new' => function ($class) { | |
return StdClass(array_merge((array)$class, array( | |
'new' => function($class) { | |
$obj = StdClass((array)$class); | |
$args = func_get_args(); | |
array_shift($args); | |
call_user_func_array(array($obj, 'init'), $args); | |
return $obj; | |
}, | |
))); | |
}, | |
'def' => function ($t, $name, $fn) { | |
$t->$name = $fn; | |
return $t; | |
}, | |
'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'); | |
$jimmy->speak(); | |
$doug = $dog->new('Doug'); | |
$doug->speak(); | |
$doug->bark(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I really just set out to make a substitute for StdClass that you could attach callable methods too, but then I realized that this was basically the same thing that dhotson had done in his oo.php, so I merged the two. This one is simpler; it leaves out the fn() method as it's pure syntactic sugar, but here we include data members as well as just methods.