-2

我的班级中有以下代码

class Mail {
    function AddAttachment($path, $name = '', $filetype = 'application/octet-stream') {
        if (!@is_file($path)){
            echo'<pre>Filepath was not found.</pre>';
        }

        if (empty($name)) {
            echo 'no filename';
        }

        //store attachment in array
        if(!isset($attachments)) {
            $attachments = array();
        }

        $attachments[] = array('path' => $path,'name' => $name,'type' => $filetype);
        //echo '<pre>';print_r($attachment);
        return  $attachments;
    }

    function SetMail() {
        foreach ($this->$attachments as $attachment) {
            echo '<pre>';print_r($attachment);
        }
    }
}

$mail = new Mail;
$mail->AddAttachment('../images/logo.png','filename');
$mail->AddAttachment('../images/logo.png','filensame');
$mail->SetMail();

如您所见,我首先为附件(addAttachment)创建数组,这很好用。虽然我似乎无法在下一个方法中使用这个数组。

我尝试公开 $attachments 属性,但仍然收到以下错误消息:

(不公开):无法访问空属性

(与公共):无法访问空属性

(当使用self::$attachments代替时$this::$attachments):访问未声明的静态属性:

谁能解释我如何将 $attachments 属性传递给 SetMail 方法?

已经谢谢了!

4

2 回答 2

1

无需将 发送attachments到该SetMail方法。它必须自动完成。您必须在类中声明attachments变量。当你想访问它时,你必须这样做$this->attachments

<?php

class Mail {
    private $attachments = array();

    function AddAttachment($path, $name = '', $filetype = 'application/octet-stream') {
        $this->attachments[] = array('path' => $path,'name' => $name,'type' => $filetype);
        return  $this->attachments;

    }

    function SetMail()  {
        foreach ($this->attachments as $attachment) {
            echo '<pre>';
            print_r($attachment);
            echo '</pre>';
        }
    }
}

$mail = new Mail;
$mail->AddAttachment('../images/logo.png','filename1');
$mail->AddAttachment('../images/logo.png','filename2');
$mail->SetMail();

?>
于 2013-05-18T12:44:25.957 回答
0

每次调用 AddAttachment 时,您都在声明一个新的 $attachments 变量

class Mail
{
    private $attachments=array();

    function AddAttachment($path, $name = '', $filetype = 'application/octet-stream')
    {
        if (!@is_file($path)){
            echo'<pre>Filepath was not found.</pre>';
        }
        if (empty($name))
        {
            echo 'no filename';
        }
        $att= array('path' => $path,'name' => $name,'type' => $filetype);

        $this->attachments[]=$att;

        return  $att;
    }
    function SetMail() 
    {
        foreach ($this->$attachments as $attachment)
        {
            echo '<pre>';print_r($attachment);
        }
    }
}
于 2013-05-18T12:48:12.673 回答