PHP致命错误:无法访问空属性

时间:2015-04-08 15:42:33

标签: php phpmailer

当我在php中编写Email类时,我一直收到此错误。

class Email {

public $mail;

function __construct() {
    $this->$mail = new PHPMailer(true);
    $this->$mail->SMTPDebug=1;

    $this->$mail->isSMTP();

    $this->$mail->SMTPAuth = true;

    $this->$mail->Host = '************'

    $this->$mail->SMTPSecure = 'ssl';

    $this->$mail->Port = 465;

    $this->$mail->Hostname = '************';

    $this->$mail->CharSet = 'UTF-8';

    $this->$mail->FromName = '*************';

    $this->$mail->Username = '*************';

    $this->$mail->Password = '**************';

    $this->$mail->From ='***********';
}

当我新建一个电子邮件类时,它说无法访问

中的空白属性
$this->$mail = new PHPMailer(true);

我试过这样做

public $mail = new PHPMailer();

它说这是语法错误。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

<强>问题:

前缀为$ character的字符串被解释为变量,这包括通过变量访问类属性:

示例:

$property = 'address';
echo $this->$property;

$property已解析为address,因此$this->$property评估为$this->address

在您的情况下,$ mail没有为其分配值,因此在访问$this->$mail时您正在访问空属性$this->并尝试分配:

$this-> = new PHPMailer();

<强>解决方案:

直接访问类属性时省略$字符。

class Email {

public $mail;

function __construct() {
    $this->mail = new PHPMailer(true);
    $this->mail->SMTPDebug=1;

    $this->mail->isSMTP();

    $this->mail->SMTPAuth = true;

    $this->mail->Host = '************'

    $this->mail->SMTPSecure = 'ssl';

    $this->mail->Port = 465;

    $this->mail->Hostname = '************';

    $this->mail->CharSet = 'UTF-8';

    $this->mail->FromName = '*************';

    $this->mail->Username = '*************';

    $this->mail->Password = '**************';

    $this->mail->From ='***********';
}