PHP Fatal error: Cannot access empty property

PHP Fatal error: Cannot access empty property

我在 php 中写电子邮件 class 时一直收到此错误。

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 ='***********';
}

当我新建一个电子邮件 Class 时,它说无法在

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

我试过这样做

public $mail = new PHPMailer();

说是语法错误

有人可以帮忙吗?

问题:

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

示例:

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

$property 被解析为 address,因此 $this->$property 计算为 $this->address

在你的情况下 $mail 没有分配给它的值,因此当访问 $this->$mail 时你正在访问空的 属性 $this-> 并试图分配:

$this-> = new PHPMailer();

解法:

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

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 ='***********';
}