2015-01-11 49 views
1

雖然我是PHP創建一個類,我經歷了這個錯誤:PHP 5.6.3解析錯誤:語法錯誤,意想不到的 '[' 類

Parse error: syntax error, unexpected '[', expecting ',' or ';' on line 5 

一個簡單的例子:

<?php 

class MyClass 
{ 
    public $variable["attribute"] = "I'm a class property!"; 
} 

?> 

我已經看過Reference - What does this error mean in PHP?,但這似乎不適合我的情況。所有其他現有問題似乎都依賴於舊的PHP版本。但我使用PHP 5.6.3!

我該怎麼辦?我只是沒有視力嗎?

+0

我不認爲你可以做到這一點,但嘗試'$變量=陣列( 「屬性」=>「我是一個類屬性!」)' – MightyPork

+0

我知道這種方式有效,但爲什麼這是一個類的外部可能? <?php $ variable [「attribute」] =「我是一個類屬性!」; ?> – DevTec

+0

只是因爲它不在類中......它會隱式地創建數組並將其設置爲元素,但是這裏看起來像是在聲明數組的「attribute」元素爲public,這很奇怪,而且php不喜歡它, – MightyPork

回答

2

不能明確創建這樣的(數組索引)的變量。你必須做這樣的:

class MyClass { 
    // you can use the short array syntax since you state you're using php version 5.6.3 
    public $variable = [ 
     'attribute' => 'property' 
    ]; 
} 

或者,你可以做(​​因爲大多數人會),這樣的:

class MyClass { 
    public $variable = array(); 

    function __construct(){ 
     $this->variable['attribute'] = 'property'; 
    } 
} 
// instantiate class 
$class = new MyClass(); 
1

我想你應該聲明它是如下的方式:

class MyClass 
{ 
    public $variable = array("attribute" => "I'm a class property!"); 
} 
1

首先製作一個陣列。使用下面

<?php 

class MyClass 
{ 
public $variable = array("attribute"=>"I'm a class property!"); 

} 

?> 

希望這可以幫助你

1

你不能聲明類成員這樣的代碼。你也不能在類成員聲明中使用表達式。

有兩種方法可以實現你在找什麼:

class MyClass 
{ 
    public $variable; 
    function __construct() 
    { 
     $variable["attribute"] = "I'm a class property!"; 
    } 
} 

或類似這樣的

class MyClass 
{ 
    public $variable = array("attribute" => "I'm a class property!"); 
} 
相關問題