我的课程中有以下代码
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属性公开,但我仍然收到以下错误消息:
(不公开):无法访问空属性
(with public):无法访问空属性
(使用self::$attachments
代替$this::$attachments
时):访问未声明的静态属性:
有人可以解释我如何将$ attachments属性传递给SetMail方法吗?
全部谢谢!
答案 0 :(得分: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();
?>
答案 1 :(得分: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);
}
}
}