PHP 5 Re-assign $this PROBLEM - any ideas?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi all
Just a quickie, in case it's been covered, like a million times or  

I'm self taught, and thought I was being pretty clever when building a  
"messaging" class.

The idea was to abstract "html email", "text email" and "sms message" up a  
layer into a "message"

To get a message started, I call on something like this:

$msg = new Message("sms");

Message (which re-assigns the $this variable) then looks something like  

class Message{
var $message_hash;
var $message_path;//this can be changed, in case stuff is moved in future...
 function ryan_Message($type=""){//starts the whole thing
  case "html"://this means an html email
   $this = new HtmlMessage();
  case "text"://this means a text mail
   $this = new TextMessage();
    case "sms"://this means an sms message
   $this = new SmsMessage();
 }// end switch
}// end function
}// end class

Each class has methods that are named the same, but act a little  
differently, so, basically, I can use the same set of commands to compose a  
message and send it, regardless of what type of message it is.

Things work fantastically under php4, but I know that when I swap over to  
php5, it's going to throw a hissy fit, because reassigning $this is not  

Aside from going around the Message class, and just starting messages of a  
particular type from scratch:

Is there some sort of cunning retro-fit I could do to the Message class, so  
I don't have to trawl through thousands of lines of code?

Any help much appreciated

Re: PHP 5 Re-assign $this PROBLEM - any ideas?


Quoted text here. Click to load it

Use a factory method.  Declare a public static method in the messaging
class that creates the appropriate type:

class Messge {
   public static function factory($msgType) {
    ... return the correct type here ...

Then just do a search & replace of all your 'new Message(' code and
replace it with 'Message::factory('...

Site Timeline