-3

My question is similar like this: Creating anonymous objects in php

the difference is I want a class to be extended by the nameless class.

EDIT: ok, its unclear, here is the example:

$anonim_obj = new stdClass(array(
    "foo" => function() { echo "foo"; }, 
    "bar" => function($bar) { echo $bar; } 
));

I want it somehow:

$anonim_obj = new stdClass extends BaseClass (array(
    "foo" => function() { echo "foo"; }, 
    "bar" => function($bar) { echo $bar; } 
));
Community
  • 1
  • 1
John Smith
  • 6,129
  • 12
  • 68
  • 123
  • What do you mean? You mean you have a class, and want to add properties to it? you can. In PHP, this is called object overloading (bad terminology): `$instance->newProperty = 123;` creates a new public property on the instance. But really, you shouldn't be doing this. Assigning methods is possible by assigning closures, but that's even more wrong, because those methods are instances of the `Closure` object themselves. Besides: on-the-fly properties are slower to access, make your code more error prone and harder to maintain – Elias Van Ootegem Sep 06 '14 at 16:14
  • updated, hopefully all clear now – John Smith Sep 07 '14 at 10:03

1 Answers1

1

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.

Community
  • 1
  • 1
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149