0

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;
    }
}
Community
  • 1
  • 1
Styphon
  • 10,304
  • 9
  • 52
  • 86
  • @kingkero The documentation only has the first array. I don't understand it enough to know what I need to do. – Styphon Nov 26 '14 at 16:49
  • That wasn't the problem but a mistake on my part. See jszobody's answer for the solution – kero Nov 26 '14 at 16:51

1 Answers1

2

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.

jszobody
  • 28,495
  • 6
  • 61
  • 72
  • True. Kohana solves this by adding these rules in the [`rules()`](http://kohanaframework.org/3.3/guide-api/Model_Auth_User#rules) method. I'm not sure overwriting the constructor is such a good idea as at least you'd need to call sth like `parent::__construct()` (no idea if that works but the point should be clear) – kero Nov 26 '14 at 16:46
  • 1
    @kingkero Yeah I was primarily explaining the core PHP issue here, and the generally recommended constructor answer. Using rules() though is clearly the way to go for this specific Kohana situation. – jszobody Nov 26 '14 at 17:02