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

时间:2013-11-12 19:50:16

标签: php

我不断收到此错误“在不在对象上下文中时使用$ 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;
    }
}

2 个答案:

答案 0 :(得分:0)

$ 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

答案 1 :(得分:0)

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并期望它能够正常工作。