常量表达式包含无效操作
Constant expression contains invalid operations
我有以下代码,其中出现错误 "PHP Fatal Error: Constant expression contains invalid operations"。当我在构造函数中定义变量时,它工作正常。我正在使用 Laravel 框架。
<?php
namespace App;
class Amazon
{
protected $serviceURL = config('api.amazon.service_url');
public function __construct()
{
}
}
我看过这个问题:
但是我的代码没有将任何东西声明为静态的,所以这没有回答我的问题。
不允许以这种方式初始化 class 属性。您必须将初始化移动到构造函数中。
如描述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');
}
}
我使用的另一种可行的替代方法是 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');
});
} }
我有以下代码,其中出现错误 "PHP Fatal Error: Constant expression contains invalid operations"。当我在构造函数中定义变量时,它工作正常。我正在使用 Laravel 框架。
<?php
namespace App;
class Amazon
{
protected $serviceURL = config('api.amazon.service_url');
public function __construct()
{
}
}
我看过这个问题:
不允许以这种方式初始化 class 属性。您必须将初始化移动到构造函数中。
如描述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');
}
}
我使用的另一种可行的替代方法是 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');
});
} }