0

I have a class with static variable:

 class MyClass {
    protected static $rules = [
         'name' => 'required'
         'help' => 'required|in:' . implode(',', custom_helper_function());
    ];
 }

I want use custom helper function in this variable and use implode. How I can do it? Now I get error:

expression is not allowed as field default value

Thanks.

7
  • Are you using any framework? Commented Mar 27, 2019 at 7:58
  • @SaadSuri yeah.. Laravel Commented Mar 27, 2019 at 7:58
  • Well... as PHP lets you know, you can't, but here's a possible workaround. Commented Mar 27, 2019 at 8:02
  • You cannot set the default value of member or class variables in php outside the constructor / function. This is why php is throwing this error. Move your initialization code to the constructor or other static class method. This is a similar issue to: stackoverflow.com/a/35037631/1345973 Commented Mar 27, 2019 at 8:04
  • @HichemBOUSSETTA that's not true. It's static so he want to use it without creating an instance of the class. Commented Mar 27, 2019 at 8:07

1 Answer 1

0

You cant use functions on variable definitions. If it was just a regular one i would suggest you to assign the value on the constructor, but being an static one then that's not possible/ makes no sense.

Then you just can't. Though you can achieve something similiar with an static function:

 class MyClass {

    public static function getRules() {
        $rules = [
         'name' => 'required',
         'help' => ( 'required|in:' . implode(',', custom_helper_function()) )
        ];
        return $rules;
    }
 }
 MyClass::getRules();

Also, don't forget to define the custom_helper_function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.