在数组中使用它会导致意外的T_Variable [英] Using this in an array is causing unexpected T_Variable
问题描述
我正在使用Kohana 3.3并尝试编写自定义验证规则,以确保用户的用户名和电子邮件地址是唯一的.我正在按照此处有Kohana文档,但是每当我尝试添加array(array($this, 'unique_email'))
时,我都会得到syntax error, unexpected '$this' (T_VARIABLE), expecting ')'
.
I'm using Kohana 3.3 and trying to write a custom validation rule to ensure that users username and e-mail address are unique. I'm following the instructions from an SO question here, and the Kohana documentation here, but whenever I try to add in array(array($this, 'unique_email'))
I get syntax error, unexpected '$this' (T_VARIABLE), expecting ')'
.
如果我放array(array('Model_User', 'unique_email'))
,我不会收到任何错误,但是为什么使用$this
会导致错误呢?为了完整起见,我在下面发布了完整的课程.
If I put array(array('Model_User', 'unique_email'))
I don't get any errors, but why would using $this
cause an error? For completeness I've posted the full class below.
class Model_User extends ORM {
protected $_rules = array(
'email' => array(
array(array($this, 'unique_email')),
)
);
public function unique_email()
{
return TRUE;
}
}
推荐答案
声明类属性时,只能使用常量值.
When declaring class properties, you can only use constant values.
请参阅: http://php.net/manual/en/language. oop5.properties.php
因此,首次声明类属性时不能使用$this
.
So you can't use $this
when first declaring your class property.
您可以在构造函数中使用$this
.因此,您可以执行以下操作:
You can use $this
in the constructor. So you could do something like this:
public function __construct() {
$this->_rules['email'] = array(
array(array($this, 'unique_email'))
);
}
Edit: kingkero points out in the comments that Kohana provides you with a rules() method, which you should probably use instead of the constructor.
这篇关于在数组中使用它会导致意外的T_Variable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!