我正在尝试使用 php 来验证电子邮件


I'm trying to use php to validate an email

我一直收到此错误"不在对象上下文中使用$this"

实例。

$axre = new Axre();
if (!filter_var($this->email, FILTER_VALIDATE_EMAIL)){
    echo "yes";
} else {
    echo"no";
}

如何进入对象上下文?

它$email受到保护,我需要保护它,因为它在表单上。

此框架中的大多数对象都是通过调用构造函数填充的,但是这个有各种各样的入口点。

class Axre extends Base {

protected $email;
protected $user_name;
protected $temp_token;
protected $sign_in_token;
protected $UserShoppingList;
function __construct($email = null) {
    if (strpos($email, '@') === false) {
        $this->sign_in_token = $email;
    } else {
        $this->email = $email;
    }
}

$this 变量是对类的当前实例的特殊引用。您正在使用没有任何意义的类之外。

从 PHP 示例

class Vegetable {
   var $edible;
   var $color;
   function Vegetable($edible, $color="green") 
   {
       $this->edible = $edible; // $this refers to the instance of vegatable
       $this->color = $color;   // ditto
   }
}
$this->variable; //This does not make sense because it's not inside an instance method
class Axre extends Base {

protected $email;
protected $user_name;
protected $temp_token;
protected $sign_in_token;
protected $UserShoppingList;
function __construct($email = null) {
    if (strpos($email, '@') === false) {
        $this->sign_in_token = $email;
    } else {
        $this->email = $email;
    }
}
function isValidEmail() {
    if (filter_var($this->email, FILTER_VALIDATE_EMAIL)) {
        return true;
    }
    return false;
}
}

现在要使用它,您只需实例化类并调用 isValidEmail 方法来获得真/假结果。

$test = new Axre($email);
$validEmail = $test->isValidEmail();

您不能在类外部使用$this并期望它正常工作。