0

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.'/';
   }

}
1
  • you can accept answer for further readers if it was helpful :) Commented Jun 5, 2015 at 11:53

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

A man always learns. But I must say I wouldn't call the error thrown an informative one.
@lesssugar No, but the error message is pretty literal: I guess the parser just isn’t intelligent enough to say, “Looks like the user’s trying to use a function/method call here, I best tell them that instead of saying I just found a random parenthesis.”

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.