Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.