0
votes

I have a helpers folder in my project root (so, outside app/ folder). In my composer.json I autoload it:

"autoload": {
        "classmap": [
            "app/Http/Controllers",
            "app/Models",
            "database",
            "libraries",
            "helpers" // <- Helpers autoloaded here
        ],
       ...
    },

The methods of the helpers are static and they work properly in views and controllers. Now I'm trying to use one helper (Helper_1.php) in the second one (Helper_2.php), like so:

    class Helper_2 {

        protected static $value = Helper_1::getValue();
        ...

    }

but on the line where the $value field is declared, I get a error:

syntax error, unexpected '(', expecting ',' or ';'

I'm not sure why this happens. The syntax is obviously correct.

Update - Helper_1.php code:

class Helper_1 {

   public static function getValue() {
       $result = ''; 

       switch (Storage::getDefaultDriver()) {
            case 'local':
                $result= URL::to('/');
                break;

            case 's3':
                $path = Storage::getDriver()->getAdapter()->getClient()->getObjectUrl(env('S3_BUCKET'), '');
                break;
        }

        return $result.'/';
   }

}
2
you can accept answer for further readers if it was helpful :) - Limon Monte

2 Answers

3
votes

PHP can't parse non-trivial expressions in initializers.

You can do this:

class Helper_2 {
    protected static $value;
}

Helper_2::$value = Helper_1::getValue();

or this:

class Helper_2 {
    protected static $value;

    static function init()
    {
        self::$value = Helper_1::getValue();
    }
}

Helper_2::init();
3
votes

The syntax is obviously correct.

It isn’t. You can’t use method calls in class property definitions, so the following is incorrect:

protected static $value = Helper_1::getValue();

You can only use simple data types like integers, strings, arrays etc.