zhuanzhou
zhuanzhou

Reputation: 2453

send email to a bunch of users class

class emailer
{
private $sender;
private $recipients;
private $subject;
private $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)
{
$result = mail($recipient, $this->subject, $this->body,
"From: {$this->sender}\r\n");
if ($result) echo "Mail successfully sent to
{$recipient}<br/>";
}
}
}

why the code write this function?

function __construct($sender)
    {
    $this->sender = $sender;
    $this->recipients = array();
    }

could i delete it? thank you.

Upvotes: 0

Views: 86

Answers (2)

David
David

Reputation: 218960

Based on your comment to the question...

That function is called a constructor. Take a look at its form:

function __construct($sender)
{
  $this->sender = $sender;
  $this->recipients = array();
}

Walking through what it's doing, the first thing you see is that it has a standardized name. In this case, __construct is reserved by the language to specify that this function is used to build an instance of an object described by this class.

Next, note that it accepts a parameter. This means that when you create an instance of the class, you'd supply that instance with a parameter. So when you create an instance, you'd do something like this:

$obj = new emailer($someSender);

What you're doing here is creating an instance of emailer and supplying it a sender parameter. This call to new is what invokes the constructor. (Essentially, it's "constructing" a "new" instance of emailer.)

Internal to the constructor, it's doing two things:

  1. Set the sender property on the object to the $someSender which was provided in the call to new.
  2. Initialize the recipients property to a new array.

Finally, note that this function doesn't return anything. It's a standardized function reserved by the language, and an implication is that what it's "returning" is a new instance of that class. In the example call above, this instance is being set to $obj.

Upvotes: 1

Yet Another Geek
Yet Another Geek

Reputation: 4289

The following function is called an constuctor, and it is made so that one can easily initialize an emailer object just using this method (by writing new then class name, then the constuctor arguments).

Example:

//One can use the constructor to create a new emailer
$emailer = new emailer("[email protected]");
//Do something with emailer ...

Upvotes: 0

Related Questions