Skip to content

Instantly share code, notes, and snippets.

@rhowardiv
Forked from dhotson/oo.php
Created October 6, 2010 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhowardiv/613443 to your computer and use it in GitHub Desktop.
Save rhowardiv/613443 to your computer and use it in GitHub Desktop.
<?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();
@rhowardiv
Copy link
Author

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.

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