As we know, creating anonymous objects in JavaScript is easy, like the code below:
var object = {
p : \"value\",
p1 : [ \"john\", \"johnny\" ]
};
Yes, it is possible! Using this simple PHP Anonymous Object class. How it works:
// define by passing in constructor
$anonim_obj = new AnObj(array(
"foo" => function() { echo "foo"; },
"bar" => function($bar) { echo $bar; }
));
$anonim_obj->foo(); // prints "foo"
$anonim_obj->bar("hello, world"); // prints "hello, world"
// define at runtime
$anonim_obj->zoo = function() { echo "zoo"; };
$anonim_obj->zoo(); // prints "zoo"
// mimic self
$anonim_obj->prop = "abc";
$anonim_obj->propMethod = function() use($anonim_obj) {
echo $anonim_obj->prop;
};
$anonim_obj->propMethod(); // prints "abc"
Of course this object is an instance of AnObj class, so it is not really anonymous, but it makes possible to define methods on the fly, like JavaScript do.