Using this in an array is causing unexpected T_Variable

天大地大妈咪最大 提交于 2019-12-12 04:34:38

问题


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 ')'.

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

回答1:


When declaring class properties, you can only use constant values.

See: http://php.net/manual/en/language.oop5.properties.php

So you can't use $this when first declaring your class property.

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.



来源:https://stackoverflow.com/questions/27154443/using-this-in-an-array-is-causing-unexpected-t-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!