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

标签 php class properties syntax-error compile-time-constant

我有以下代码,其中出现错误“PHP fatal error :常量表达式包含无效操作”。当我在构造函数中定义变量时,它工作得很好。我正在使用 Laravel 框架。

<?php

namespace App;

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

    public function __construct()
    {
    }

}

我看到过这个问题:PHP Error : Fatal error: Constant expression contains invalid operations 但我的代码没有将任何内容声明为静态,因此这没有回答我的问题。

最佳答案

如上所述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.

完成这项工作的唯一方法是:-

<?php

namespace App;

class Amazon
{
  protected $serviceURL;

  public function __construct()
  {
    $this->serviceURL = config('api.amazon.service_url');
  }
}

关于php - 常量表达式包含无效操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50828988/

相关文章:

wpf - 从 XAML 设置 ViewModel 属性值

javascript - 操作对象文字: add property in certain order

PHP 和字符串字数统计

c++ - 另一个类中的自定义类实例数组崩溃编译器

C++ 类文件

javascript - 获取 javascript 函数实例本身以启用文档字符串。是否可以?

javascript - 分配 javascript 对象属性时出现问题

php - 在 MySQL 中使用 LIKE 子句优化表以进行搜索

php - 如何测试字符串是否包含 PHPUnit 中的另一个字符串?

php - Ajax 调用在 WordPress 中无法正常工作