2012-01-06 46 views
9

任何人都可以告訴我爲什麼這不起作用嗎?這只是我試圖在其他地方做的一個簡單例子。將__DIR__常量與字符串串聯起來作爲PHP中的一個類成員的數組值

$stuff = array(
    'key' => __DIR__ . 'value' 
); 

然而,這將產生一個錯誤:

PHP Parse error: syntax error, unexpected '.', expecting ')' in /var/www/.../testing.php on line 6 

而且,這個工程:

$stuff = array(
    'key' => "{__DIR__} value" 
); 
+1

感謝您的快速反應ManseUK。 爲了更好地理解我的問題 - 它返回了什麼? 我var_dump了它: 字符串(26)「/var/www/../trunk」 – acairns 2012-01-06 15:17:58

+1

在您的構造函數中設置$ stuff值 – Gerep 2012-01-06 15:18:13

回答

7

的第一段代碼不起作用,因爲它不是一個常量表達式,如您試圖連接兩個字符串。初始類成員必須是常量。

documentation

[property] 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.

+0

因此,因爲__ DIR __是當前文件的位置,所以它的運行時信息不可用在編譯時。 謝謝蒂姆。 – acairns 2012-01-06 15:24:35

+1

@acairns:不完全。在編譯腳本時,PHP的值爲'__DIR__',正如您在初始化字符串時看到的那樣:'「{__DIR__} value」'。如何訪問魔術常數是唯一的區別,其中一個被視爲常量表達式,另一個不是。 – 2012-01-06 15:28:32

3

你不能在屬性初始化使用運營商。解決方法是使用構造函數:

public function __construct() 
{ 
    $this->stuff = array(
     'key' => __DIR__ . 'value' 
); 
} 

從PHP文檔:

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.

http://www.php.net/manual/en/language.oop5.properties.php

0

設置$的東西價值在你的構造

function __construct() 
{ 
$this->$stuff = array(
     'key' => __DIR__ . 'value' 
    ); 
} 
相關問題