2014-01-20 50 views
0

意思我剛剛碰到過這樣的一段代碼:我不undrestand爲什麼他們在這裏用大括號

// Assign initialized properties to the current object 
foreach ($init as $property => $value) 
{ 
    $this->{$property} = $value; 
} 

。如果沒有它們,它會不會是一樣的$this->$property = $value;

+0

@elclanrs,使用的答案來回答:^) – sectus

+0

@sectus ...太滑稽elclanrs有32K代表... prob知道何時使用而不使用答案,哈哈。 –

+1

有幾個dups,ie http://stackoverflow.com/questions/9056021/curly-braces-notation-in-php – elclanrs

回答

1

有在你的例子沒有優勢,但是它可能已被使用的一致性。在這裏你可以使用大括號,以確保PHP可以解析你正在嘗試做榜樣(訪問動態屬性):

// Dummy object 
$obj = new stdClass(); 
$obj->color = 'green'; 

// The dynamic property we want is slightly more complex 
$tmp = array('wantProp'=>'color'); 

// ... so let's use curly braces 
echo $obj->{$tmp['wantProp']}; 
1

你是對的,就好像你沒有花括號一樣。對我來說,讓他們在這裏沒有任何意義。通常,在字符串文字中找到變量周圍的大括號來消除歧義。

例如,

$a = " $b->something says hello."; 

這是不明確的,因爲你意思了把$ B,其次是「 - >東西」或對象$ B的「東西」屬性。通常PHP可以解決這個問題,但這樣做好多了:

$a = " {$b->something} says hello."; 

由於大括號可以消除歧義。

問候, 拉爾夫

相關問題