【问题标题】:PHP throw new exception not workingPHP抛出新异常不起作用
【发布时间】:2013-09-25 01:15:22
【问题描述】:

我在 PHP 中创建了一个电子邮件类,但即使发布数据为空,它也总是返回成功。异常显然不起作用,我想知道为什么它也不发送任何电子邮件。代码如下:

<?php

class Contact
{
    private $toEmail = 'example@outlook.com', $subject = 'Personal Site - Contact';
    private $name, $email, $message;

public function __constructor(array $arr)
{
    if(!empty($arr['name']) && !empty($arr['email']) && !empty($arr['msg']))
    {
        $this->name = $this->ValidateName($arr['name']);
        $this->email = $this->ValidateEmail($arr['email']);
        $this->msg = $this->SanitizeMessage($arr['msg']);

        $this->SendMail($this->name, $this->email, $this->msg);
    }
    else
    {
        throw new Exception("Please fill all the required fields");
    }
}

private function ValidateName($name)
{
    if(ctype_alpha($name))
    {
        return $name;
    }
    else
    {
        return null;
    }
}

private function ValidateEmail($email)
{
    if(filter_var($email, FILTER_VALIDATE_EMAIL))
    {
        return $email;
    }
    else
    {
        return null;
    }
}

private function SanitizeMessage($msg)
{
    return htmlentities($msg);
}

private function SendMail($name, $email, $msg)
{
    $mailHeader = "From: " . $email . "\r\n"; 
    $mailHeader .= "Reply-To: " . $email . "\r\n"; 
    $mailHeader .= "Content-type: text/html; charset=iso-8859-1\r\n";

    $messageBody = "Name: " . $name . "";
    $messageBody .= "Email: " . $email . "";
    $messageBody .= "Comment: " . nl2br($msg) . "";

    if(mail($this->toEmail, $this->subject, $messageBody, $mailHeader))
    {
        return true;
    }
    else
    {
        throw new Exception('Message couldn\'t be sent');
    }
}
}

try
{
    $obj = new Contact($_POST);
}
catch(Exception $ex)
{
    echo json_encode($ex);
}

echo json_encode('Message was sent succesfully');

?>

【问题讨论】:

  • 大声笑...错误的帖子。对不起。
  • 为什么会有一个叫__constructor的方法??
  • 您可能需要考虑让ValidateX 方法抛出一个异常,并在__construct 中使用try/catch 捕获它,然后再抛出。这样一来,所有无效调用都会导致可捕获的异常,而不是一些返回 null
  • 另外,Contact 不是类的好名称,因为它可以解释为名词(对象存储记录)或动词(对象执行操作)。事实上,如果它不存储任何东西而只执行一个动作并在构造函数中这样做,它也应该声明为static

标签: php class email exception throw


【解决方案1】:

构造函数是__construct(),而不是__constructor()。该函数永远不会被调用。
此外,避免在构造函数中执行操作、设置变量,这没关系,但实际上在创建新对象时发送邮件对于大多数开发人员来说是出乎意料的。

【讨论】:

  • 我实际上使用了我的 ide 自动完成功能来完成那个 o.O,我试试 thx
猜你喜欢
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 2019-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-07
相关资源
最近更新 更多