Constant expression contains invalid operations [duplicate]

无人久伴 提交于 2019-11-27 08:53:35

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');
  }
}

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

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');
        });
    } }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!