Safouen
Safouen

Reputation: 133

Laravel localization class variables

I am having problem with defining class variables for example when validation a form here is the source code

class LoginFormRequest extends DefaultFormRequest
{


    protected $rulesMessages = [
        'name' => [
            'required' => trans('messages.enter_username')
        ],
        'password' => [
            'required' => trans('messages.enter_password')
        ]
    ];

}

the return error is "syntax error, unexpected '(', expecting ']'"

Upvotes: 0

Views: 355

Answers (2)

Jeff Lambert
Jeff Lambert

Reputation: 24661

Any value that any class property is allowed to be initialized to must be constant (I do not mean the property itself, I mean the data you are trying to initialize it to). All this means is that whatever it is must be known at compile time rather than run time, so it cannot be dependent on any other code actually running prior to being able to extract the value you are attempting to initialize the property to. This is why it is a compiler (syntax) error rather than a runtime error. Relevant quote from the manual:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

All of the following are valid class property initializations:

class One
{
    protected $one = 'One';
}

class Two
{
    protected $two = 2;
}

class Three
{
    protected $three = [
        1 => 'one',
        2 => 'two'
    ];
}

// We can use constants defined using const keyword, because they are 
// evaluated at compile time. See http://stackoverflow.com/a/3193704/697370
const FOUR_CONST = 4;
class Four
{
    protected $four = FOUR_CONST;
}

The following are invalid class property initializations:

class BadOne
{
    protected $one = foo();
}

$IamAboolean = false;
class BadTwo
{
    protected $two = $IamAboolean ? false : true;
}

class BadThree
{
    protected $three = 5 + 4;
}

Upvotes: 1

Matt McDonald
Matt McDonald

Reputation: 5050

Try moving them into the __construct method.

public function __construct()
{
    $this -> rulesMessages = [
        'name' => [
            'required' => trans('messages.enter_username')
        ],
        'password' => [
            'required' => trans('messages.enter_password')
        ]
    ];
}

Upvotes: 1

Related Questions