php 常量表达式包含无效操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40827870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:16:03  来源:igfitidea点击:

Constant expression contains invalid operations

phpclasspropertiessyntax-errorcompile-time-constant

提问by Aaron

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 致命错误:常量表达式包含无效操作”。当我在构造函数中定义变量时,它工作正常。我正在使用 Laravel 框架。

<?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 operationsBut my code does not declare anything as static, so that did not answer my question.

我见过这个问题:PHP 错误:致命错误:常量表达式包含无效操作但我的代码没有将任何内容声明为静态,因此没有回答我的问题。

回答by prateekkathal

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.

类成员变量称为“属性”。您可能还会看到使用其他术语(例如“属性”或“字段”)来引用它们,但出于此引用的目的,我们将使用“属性”。它们是通过使用关键字 public、protected 或 private 之一来定义的,后跟一个普通的变量声明。这个声明可能包括一个初始化,但这个初始化必须是一个常量值——也就是说,它必须能够在编译时被评估,并且必须不依赖于运行时信息才能被评估。

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

回答by Curos

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

不允许以这种方式初始化类属性。您必须将初始化移动到构造函数中。

回答by 4givN

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

我使用的另一个工作替代方案是boot( )使用 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');
        });
    } }