nmartins
nmartins

Reputation: 185

Object property not recognized as an array

I have a PHP Class named Mail and in another class I want to do the following:

if (is_array ( $mail->getToAddresses () )) {
        foreach ( $mail->getToAddresses () as $address ) {
            $mailer->addAddress ( $address );
        }
}

but the if condition does not match. It never enters the foreach code... How can I indicate that that property is really an array? Any ideias?

Mail class:

class Mail {

private $from;
private $fromName;
private $subject;
private $toAddresses;
private $ccAddresses;
private $bccAddresses;
private $message;

public function __construct() {
    $this->toAddresses = array();
    $this->ccAddresses = array();
    $this->bccAddresses = array();
}

public function addToAddress($toAddress) {
    $this->toAddresses = $toAddress;
}

public function addCcAddress($ccAddress) {
    $this->ccAddresses = $ccAddress;
}

public function addBccAddress($bccAddress) {
    $this->bccAddresses = $bccAddress;
}

public function getFrom() {
    return $this->from;
}

public function setFrom($from) {
    $this->from = $from;
}

public function getFromName() {
    return $this->fromName;
}

public function setFromName($fromName) {
    $this->fromName = $fromName;
}

public function getSubject() {
    return $this->subject;
}

public function setSubject($subject) {
    $this->subject = $subject;
}

public function getToAddresses() {
    return $this->toAddresses;
}

public function setToAddresses($toAddresses) {
    $this->toAddresses = $toAddresses;
}

public function getCcAddresses() {
    return $this->ccAddresses;
}

public function setCcAddresses($ccAddresses) {
    $this->ccAddresses = $ccAddresses;
}

public function getBccAddresses() {
    return $this->bccAddresses;
}

public function setBccAddresses($bccAddresses) {
    $this->bccAddresses = $bccAddresses;
}

public function getMessage() {
    return $this->message;
}

public function setMessage($message) {
    $this->message = $message;
}

public function __toString() {
    return "from=" . $this->from . ", fromName=" . $this->fromName . ", subject=" . $this->subject . ", message=" . $this->message; 
}

Upvotes: 0

Views: 142

Answers (1)

lafor
lafor

Reputation: 12776

Your addToAddress() method overwrites the toAddresses property (therefore making it a string). I believe you wanted to add to the toAddresses array there instead:

public function addToAddress($toAddress) {
    $this->toAddresses[] = $toAddress;
}

Also, you might wanna add a type hint to the setToAddresses() setter, so it doesn't accept non-arrays:

public function setToAddresses(array $toAddresses) {
    $this->toAddresses = $toAddresses;
}

Upvotes: 1

Related Questions