在数组中使用它会导致意外的T_Variable [英] Using this in an array is causing unexpected T_Variable

查看:73
本文介绍了在数组中使用它会导致意外的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'))
    );
}

编辑:kingkero在评论中指出Kohana为您提供了

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆