deadimp Posted September 16, 2007 Share Posted September 16, 2007 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 More sharing options...
Jenk Posted September 21, 2007 Share Posted September 21, 2007 Possibly with Reflection, but it won't be as "easy" Link to comment https://forums.phpfreaks.com/topic/69601-anonymous-classes-with-methods/#findComment-352234 Share on other sites More sharing options...
448191 Posted September 21, 2007 Share Posted September 21, 2007 It's not exactly what you're looking for, but: http://www.php.net/manual/en/function.create-function.php Link to comment https://forums.phpfreaks.com/topic/69601-anonymous-classes-with-methods/#findComment-352644 Share on other sites More sharing options...
deadimp Posted September 23, 2007 Author Share Posted September 23, 2007 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. Link to comment https://forums.phpfreaks.com/topic/69601-anonymous-classes-with-methods/#findComment-353212 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.