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.

Dronax
  • 259
  • 2
  • 4
  • 15
  • Are you using any framework? – Saad Suri Mar 27 '19 at 07:58
  • @SaadSuri yeah.. Laravel – Dronax Mar 27 '19 at 07:58
  • Well... as PHP lets you know, you can't, but [here's a possible workaround](https://stackoverflow.com/a/3312881/965834). – Jeto Mar 27 '19 at 08: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: https://stackoverflow.com/a/35037631/1345973 – Hichem BOUSSETTA Mar 27 '19 at 08:04
  • @HichemBOUSSETTA that's not true. It's static so he want to use it without creating an instance of the class. – Elanochecer Mar 27 '19 at 08:07
  • @Elanochecer yes I've just seen the variable is static. still, it cannot be initialized outside a function bloc. I updated my comment. thanks – Hichem BOUSSETTA Mar 27 '19 at 08:08
  • This defeats the purpose of a static variable. – Daniel W. Mar 27 '19 at 10:11

1 Answers1

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.

Elanochecer
  • 600
  • 3
  • 8