【问题标题】:Why would the selfsame code instanciating PHPMailer work in one file/directory and not work in another?为什么实例化 PHPMailer 的相同代码在一个文件/目录中工作而在另一个文件/目录中不起作用?
【发布时间】:2022-01-20 20:31:23
【问题描述】:

附加代码在我们的服务器上完美运行。

仅供参考,注释掉的 require() 语句会加载一个文件,该文件包含其后的每一行内容。

当我取消注释 require() 语句,然后注释掉它下面的相同内容时,就会出现问题。

当我这样做时,突然 PHPMailer 对象拒绝实例化。

我对所有文件/文件夹都有双重检查权限,它们都很好。

这真是让人头疼。

帮助!

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require( CLASSES . "src/PHPMailer.php"  );
require( CLASSES . "src/SMTP.php"       );
require( CLASSES . "src/Exception.php"  );

//  require( 'receipt_email.php' );

$email = new PHPMailer();

try
    $email->IsSMTP();
    $email->SMTPDebug   = 0;
    $email->SMTPAuth    = TRUE;
    $email->Host        = SERVER_NAME;
    $email->SMTPSecure  = "tls";
    $email->Port        = "587";
    $email->Username    = MAIL_ACCTNAME;
    $email->Password    = MAIL_PASSWORD;
    $email->FromName    = "do_not_reply@lcus.edu";
    $email->From        = "LCUonline";
    $email->Subject     = "TEST MESSAGE";
    $email->Body        = "TEST MESSAGE BODY";
    $email->AddAddress( "developer@lcus.edu", "Dr. Steve Willis" );

    echo $email->Send() ? "SUCCESS" : "FAILED";
}

catch( Exception $e ) {
    echo "Message could not be sent. Mailer Error: {$email->ErrorInfo}";
}

unset( $email );

【问题讨论】:

    标签: object phpmailer


    【解决方案1】:

    这是因为您不了解use 语句的工作原理。它们是本地别名,应用于它们出现的文件as the docs say。因此,如果您将它们放在一个文件中,并在另一个文件中有一个命名空间类实例化,那么它将无法正常工作,正如您所发现的那样。你的情况下的分离应该是这样的:

    在第一个文件中:

    require( CLASSES . "src/PHPMailer.php"  );
    require( CLASSES . "src/SMTP.php"       );
    require( CLASSES . "src/Exception.php"  );
    
    require( 'receipt_email.php' );
    

    receipt_email.php:

    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    $email = new PHPMailer();
    

    除其他外,这就是为什么真正值得学习如何使用 composer,因为它极大地简化了这些事情。

    【讨论】:

    • 我不能使用作曲家。刚试过。由于其他软件依赖项,我们被困在 PHP v7.1 上,而 composer 需要 v7.2。那么我还能做些什么来完成这项工作呢?
    • Composer 不需要 PHP 7.2;它与 PHP 5.4 左右兼容。
    • 那为什么我会收到一条致命错误消息,说明我刚才所说的内容?
    • 我不知道,因为您没有发布错误的文本。
    • 我将 use 语句添加到实例化 $email 对象的 require() 文件的顶部。还是失败!使用 PHPMailer\PHPMailer\PHPMailer;使用 PHPMailer\PHPMailer\Exception;使用 PHPMailer\PHPMailer\SMTP; $email = new PHPMailer();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多