[Solved] Creating anonymous objects in php, which extends something


What you’re trying to do is impossibru!. Can’t be done, no way. Forget about it. End of.
An anonymous object is indeed an instance of the stdClass, but you can’t in-line-extend it. What you can do, however, is to create an instance of the base class you want the stdClass to extend from, and overload it (which is a bad idea IMO, but it’s poissible):

$anonObj = new BaseClass();//create "parent" instance
$anonObj->foo = function()
{
    echo 'foo';
};
$anonObj->bar = function($bar)
{
    echo $bar;
};

The reason why I consider this “overloading” to be a bad idea is because of:

  • Overloading is just a silly term, most of the time overloading, in OOP, means something else entirely
  • Predeclared properties are quick to find, properties added to an instance are not. details here
  • Typo’s make your code extremely vulnerable to errors, and neigh on impossible to debug
  • You can type-hint for a class, which tells you certain pre-defined methods and properties will be available. If you add properties/methods as you go, you loose this edge

Bottom line: if you want an object to extend your BaseClass, and have 2 extra methods: just write the bloody class, don’t try to extend generic objects from custom made ones.

0

solved Creating anonymous objects in php, which extends something