Constant expression contains invalid operations [duplicate]
Asked Answered
W

3

32

I have the following code, where I get the error "PHP Fatal Error: Constant expression contains invalid operations". It works fine when I define the variable in the constructor. I am using Laravel framework.

<?php

namespace App;

class Amazon
{
    protected $serviceURL = config('api.amazon.service_url');

    public function __construct()
    {
    }

}

I have seen this question: PHP Error : Fatal error: Constant expression contains invalid operations But my code does not declare anything as static, so that did not answer my question.

Wolfsbane answered 27/11, 2016 at 10:24 Comment(2)
you can't use functions at that point, move it to the constructorDistributee
you need to assign serviceURL value inside the construct() functionHulton
U
85

As described here

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. 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.

The only way you can make this work is :-

<?php

namespace App;

class Amazon
{
  protected $serviceURL;

  public function __construct()
  {
    $this->serviceURL = config('api.amazon.service_url');
  }
}
Unlace answered 27/11, 2016 at 11:57 Comment(0)
M
4

Initializing class properties is not allowed this way. You must move the initialization into the constructor.

Messily answered 27/11, 2016 at 10:30 Comment(0)
M
0

Another working alternative I used is with boot( ) with Laravel Eloquent:

<?php

namespace App;

class Amazon {
    protected $serviceURL;

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model){
            $model->serviceURL = config('api.amazon.service_url');
        });
    } }
Martineau answered 14/7, 2018 at 15:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.