Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using array_push in method in php

Tags:

php

The addRecipients use push_array but it does not work. What am I doing wrong here??

In class.emailer.php

class Emailer
{
public $sender;
public $recipients;
public $subject;
public $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()
{
    echo "From sendEmail, send email initiated<br />";
    echo "Body: ".$this->body."<br />";
    echo "Subject: ".$this->subject."<br />";
    print_r ($this->sender);
    print_r ($this->recipients);
    echo "<br />";
    foreach ($this->recipients as $recipient)
    {
        echo "6<br />";
        //$result = mail($recipient, $this->subject, $this->body,"From: {$this->sender}\r\n");
        echo "7<br />";
        if ($result) echo "Mail successfully sent to {$recipient}<br/>";
    }
}

}

And in class.extendedemailer.php

include_once("class.emailer.php"); 

class ExtendedEmailer extends emailer
{
function  __construct(){
    //overwriting __contruct here   
}

public function setSender($sender)
{
    $this->sender = $sender;
}
}

And in sendemail.php

    include_once("class.extendedemailer.php"); 
echo "start 1<br />";
$xemailer = new ExtendedEmailer(); 

echo "1. adding sender: <br />";
$xemailer->setSender("[email protected]"); 
print_r ($xemailer->sender);
echo "<br />2. adding recipients: <br />";
$xemailer->addRecipients("[email protected]"); 
var_dump ($xemailer->recipients);
echo "<br />3. adding subject: <br />";
$xemailer->setSubject("Just a Test<br />"); 
print_r ($xemailer->subject);
echo "4. adding body<br />";
$xemailer->setBody("Hi, How are you?<br />"); 
print_r ($xemailer->body);
echo "5. sending email<br />";
$xemailer->sendEmail();

The output of recipients is NULL.

start 1
1. adding sender: 
[email protected]
2. adding recipients: 
NULL 
3. adding subject: 
Just a Test
4. adding body
Hi, How are you?
5. sending email
From sendEmail, send email initiated
Body: Hi, How are you?

Subject: Just a Test
like image 814
shin Avatar asked Feb 10 '26 20:02

shin


1 Answers

You are probably not initiating $recipients when you rewrote the constructor.

class Emailer {
    public $recipients = array();

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

Should do it. Check your warnings for

Warning: array_push() expects parameter 1 to be array, null given in ...

like image 104
kero Avatar answered Feb 13 '26 03:02

kero