常量表达式包含无效操作 [英] Constant expression contains invalid operations

查看:40
本文介绍了常量表达式包含无效操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,其中出现错误PHP 致命错误:常量表达式包含无效操作".当我在构造函数中定义变量时,它工作正常.我正在使用 Laravel 框架.

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()
    {
    }

}

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

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.

推荐答案

如上所述 这里

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

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

这篇关于常量表达式包含无效操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆