为什么我得到 $mail 对象的空值?

Why am i getting null value for the $mail object?

我正在使用代码查找延迟入住的人并向他们发送电子邮件。我还发现那些根本没有来的人,也给他们发了电子邮件。但是,它不起作用。我正确获取了姓名和电子邮件,但 $mail 对象为空,我不明白为什么。

这是我的代码:

mail_sender.php(这是我发送消息的调用)

<?php

function custom_mail($name, $surname, $email, $message, $subject){
    //$mail->SMTPDebug = 3;                               // Enable verbose debug output
        require './PHPMailer-master/PHPMailerAutoload.php';
        $mail = new PHPMailer();
        global $mail;
        var_dump($mail); 
        $mail->isSMTP();                                      // Set mailer to use SMTP
        $mail->Host = 'smtp.gmail.com;';  // Specify main and backup SMTP servers
        $mail->SMTPAuth = true;                               // Enable SMTP authentication
        $mail->Username = '****';                 // SMTP username
        $mail->Password = '****';                           // SMTP password

        $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
        $mail->Port = ****;                                    // TCP port to connect to        
        $mail->From = '****';
        $mail->FromName = '****';

        $mail->addAddress($email, $name." ".$surname);     // Add a recipient
        $mail->addCC('****');
        $mail->isHTML(true);                                  // Set email format to HTML   
        $mail->Subject = $subject;
        $mail->Body    = ucwords($name).' '.ucwords($surname).'! <br />'.$message;
        $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
        //
        if(!$mail->send()) {
                echo 'email -> '.$email.' name -> '.$name.' surname -> '.$surname.'<br />';
                echo 'Mailer Error: ' . $mail->ErrorInfo;
        } 
        else    {                           
                    $mail->ClearAllRecipients();        //clears the list of recipients to avoid other people from getting this email               
        }   
}   

?>

我想这可能是你的问题:

$mail = new PHPMailer();
global $mail;
var_dump($mail);

这看起来不是个好主意 - 如果您已经全局定义了一个名为 $mail 的变量,它可能会覆盖您的 PHPMailer 实例,使其成为 null。将顺序更改为:

global $mail;
$mail = new PHPMailer();
var_dump($mail);

我看不出有太多理由让它在全球范围内可用 - 如果你想在多个调用中重复使用该实例,这无济于事 - 你应该静态地声明它来做到这一点,像这样:

static $mail;
if (!isset($mail)) {
    $mail = new PHPMailer();
}
var_dump($mail);