我的类中有以下代码
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属性,但我仍然收到以下错误消息:
(没有公共(:无法访问空属性
(带public(:无法访问空属性
(使用self::$attachments
而不是$this::$attachments
时(:访问未声明的静态属性:
有人能解释我如何将$attachments属性传递给SetMail方法吗?
谢谢大家准备好了!
不需要将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();
?>
每次调用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);
}
}
}