对象属性未被识别为数组

时间:2014-02-12 12:17:46

标签: php

我有一个名为Mail的PHP类,而在另一个类中我想要执行以下操作:

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

但if条件不匹配。它永远不会进入foreach代码...... 我如何表明该属性确实是一个数组? 任何想法?

邮件类:

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; 
}

1 个答案:

答案 0 :(得分:1)

您的addToAddress()方法会覆盖toAddresses属性(因此将其设为字符串)。我相信你想在那里添加toAddresses数组:

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

此外,您可能希望向setToAddresses() setter添加类型提示,因此它不接受非数组:

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