2016-11-27 56 views
7

我有以下代碼,其中出現錯誤「PHP致命錯誤:常量表達式包含無效操作」。當我在構造函數中定義變量時,它工作正常。我正在使用Laravel框架。常量表達式包含無效操作

<?php 

namespace App; 

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

    public function __construct() 
    { 
    } 

} 
+0

你不能在這一點上使用的功能,將它移動到 – RST

+0

你需要構造在construct()函數內分配serviceURL值 –

回答

11

如上所述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'); 
    } 
} 
0

以這種方式不允許初始化類屬性。您必須將初始化移動到構造函數中。

相關問題