PHP函数不返回null但也不返回任何内容

Here is my code, which uses an extended phpMailer. This works if I check for firstResult and lastResult, but not if I check for emailResult:

$validator = new FormValidator();
            $firstResult = $validator->checkFirst($_POST['firstname']);
            $lastResult = $validator->checkLast($_POST['lastname']);
            $emailResult = $validator->checkEmail($_POST['emailaddress1']);
            var_dump($emailResult);
            if (is_null($firstResult) && is_null($lastResult) && is_null($emailResult)) {

                $mail = new ULSMail();

                $mail->IsSMTP();  // telling the class to use SMTP
                $mail->AddAddress("shummel@ulsinc.com");

                $mail->Subject  = "test";
                $mail->MsgHTML($messageHTML);

                redirectULS('english/forms/thankyou.php');

                if(!$mail->Send()) {
                    echo 'Message was not sent.';
                    echo 'Mailer error: ' . $mail->ErrorInfo;
                } else {

                    //$bridge->pushLead($lead);
                }
            } else {
                //...
            }

and in my FormValidator class:

function checkEmail($email){

        if(strlen(trim($email)) < 8){
        return 'Please enter a valid email address of more than 8 characters</span>';
    } else {
        return NULL;
    }

}

redirectULS is a simple redirect function for internal redirects on my site. It works as long as I don't check for $emailResult.

Actually, it does!

if (checkEmail("123456789") === NULL)
  print "Actually, it does!
";

What you're doing is printing the result directly, which will cast NULL to an empty string. Hence it only appears to return nothing.

Notice that I made use of the triple equals operator, which tests for equality in value AND type. As @Tomcat suggests, you can also use is_null()

Actually, it returns NULL when your string is lower than 8. Try var_dump instead of echo/print, it should display the "real" value (=NULL) of your string.

How are you testing the return?

echo is_null(checkEmail('foo@bar.com')) ? 'Pass' : 'Fail';

Also just a note; your validation parameters of 8 characters will fail on an email such as j@cc.tv. While surely rare, it would be suggested you validate based on form using Regular Expressions. Plenty of examples on the web.


class Validator{

    public function checkEmail($email){
        return preg_match('/^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', $email);
    }

    public function checkName($name){
        return preg_match('/[a-z]{2,}/i', $name); //valid if $name is 2+ A-Z characters
    }

}

$v = new Validator;
if($v->checkEmail($_POST['email'])
&& $v->checkName($_POST['fname'])
&& $v->checkName($_POST['lname'])){
    //the info is valid
}else{
    //the info is not valid
}