jug Posted April 9, 2009 Share Posted April 9, 2009 Hi, im reasonably new to OOP in PHP and as i have been used to procedural programming for quite some time i probably have quite a few bad habits i need to erase. My question is simply this: I have got an class email class (though this question i think is universal for any situation) which is structured as follows. class email { protected $sender; protected $recipients; protected $subject; protected $body; function __construct($sender){ $this->sender = $sender; $this->recipients = array(); } public function addRecipients($recipient){ array_push($this->recipients, $recipient); } public function setSubject($subject){ $this->subject = $subject; } public function setBody($body){ $this->body = $body; } public function sendEmail(){ foreach($this->recipients as $recipient){ mail($recipient, $this->subject, $this->body, $headers); } } } The above works fine and is what im going to use but whats stopping me from just doing something like the following? class email { public function __construct(){} public function sendEmail($to, $subject, $reply, $body){ mail($to, $subject, $body, $headers); } } Both classes will work fine and will give the same output/results. I suppose i want to know where to you draw the line at passing parameters and although its clear that the first example is visually better, why is it better theoretically? Links to good articles would be very much appreciated and if anyone know where i could find an example of the same piece of code in both procedural and object-oriented that would help a lot. Im self taught hence why im asking these prob simple design questions. Thanks in advance Quote Link to comment Share on other sites More sharing options...
KevinM1 Posted April 9, 2009 Share Posted April 9, 2009 The above works fine and is what im going to use but whats stopping me from just doing something like the following? Well, your second example is essentially just a wrapper to a function. If you're going to do that, you might as well just access the function directly. OO doesn't mean "stuff everything into an object." The whole point is to hide how things are implemented behind a clear, concise interface in order to promote modular, extensible, reusable code. The interface remains the same, allowing the underlying bits to be modified without completely breaking the system. In your specific email case, I'd only use an object if you need to maintain that list of recipients and keep them associated with the rest of the mail details (subject, body). If it's a one-shot deal, and no other objects need to pass that mail info around, then I'd just use the built-in function without an object wrapper. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.