-1

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

2 回答 2

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;
}

}

Now to use it you can just instantiate the class and call the isValidEmail method to get a true/false result.

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

You can't use $this outside of a class and expect it to work.

于 2013-11-12T20:28:09.947 回答
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
于 2013-11-12T19:57:10.523 回答