Jump to content

Anonymous classes [with methods]?


deadimp

Recommended Posts

I'm just curious: Is there a possibility of anonymous classes with methods in PHP?

Something like JavaScript or C++:

//JS - Rough sketch
var obj={
name: "Bob",
explain: function() { return this.name+" es tan padre"; }
};
document.write(obj.explain());

//C++
struct {
string name;
//No ctor because of C++'s definition style
string explain() { return name+" es tan padre"; }
} obj;
obj.name="Bob";
cout << obj.explain();

Each one will output "Bob es tan padre".

 

I know you can use a blank stdClass, a null variable, or an array that's converted using the object operator to create an object, but as far as I know you can only define variables.

 

EDIT: Err... Corrected my JS code.

 

Another thing I'm looking for, if this is even possible in PHP, is inheritance with anonymous classes. I know you can do this in C++:

struct Test {
virtual void blarg() { cout << "Nadie"; }
}
...
struct : public Test {
void blarg() {
  Test::blarg();
  cout << " es el mejor";
}
} bob;
Test *ptr=&bob;
ptr->blarg();

Output: "Nadie es el mejor"

Of course, with C++, the classes are scoped, so you could name a class inside a function or whatever and not really have to worry about collision (which isn't the case with PHP).

Link to comment
https://forums.phpfreaks.com/topic/69601-anonymous-classes-with-methods/
Share on other sites

I didn't see anything in the PHP Manual on Reflection on how you could create anonymous classes, and create_function() has it all defined via strings and doesn't have a natural feel to it.

I was doubtful when I posted this, I was just hoping there was some hidden feature in there somewheres.

Thanks for the info.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.