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.
Based on your comment to the question…
That function is called a constructor. Take a look at its form:
Walking through what it’s doing, the first thing you see is that it has a standardized name. In this case,
__constructis 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:
What you’re doing here is creating an instance of
emailerand supplying it asenderparameter. This call tonewis what invokes the constructor. (Essentially, it’s “constructing” a “new” instance ofemailer.)Internal to the constructor, it’s doing two things:
senderproperty on the object to the$someSenderwhich was provided in the call tonew.recipientsproperty 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.