2012-04-23 9 views

Odpowiedz

4

W twoim przykładzie nie ma różnicy. Jest to jednak pomocne, gdy wyrażenie zmiennej jest bardziej złożone, jak tablica z indeksem ciągów. Na przykład:

$arr['string'] = 'thing'; 

echo "Print a {$arr['string']}"; 
// result: "Print a thing"; 

echo "Print a $arr['string']"; 
// result: Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE 
+0

Ahh, widzę, dziękuję bardzo. – Andy

4

Od PHP.net

Complex (kręcone) składnia

ten nie jest nazywany złożonym, ponieważ składnia jest złożona, ale ponieważ pozwala na użycie złożonego wyrażenia ns.

Dowolna zmienna skalarna, element tablicy lub właściwość obiektu z ciągiem reprezentacja może być zawarta za pośrednictwem tej składni. Po prostu napisz wyrażenie w ten sam sposób, w jaki pojawi się on poza ciągiem, a następnie , a następnie zawiń go w {i}. Ponieważ {nie może być zmieniona, składnia ta będzie rozpoznawana tylko wtedy, gdy $ natychmiast podąża za {. Użyj {\ $ do , aby uzyskać dosłowny {$.

przykład:

<?php 
// Show all errors 
error_reporting(E_ALL); 

$great = 'fantastic'; 

// Won't work, outputs: This is { fantastic} 
echo "This is { $great}"; 

// Works, outputs: This is fantastic 
echo "This is {$great}"; 
echo "This is ${great}"; 

// Works 
echo "This square is {$square->width}00 centimeters broad."; 


// Works, quoted keys only work using the curly brace syntax 
echo "This works: {$arr['key']}"; 


// Works 
echo "This works: {$arr[4][3]}"; 

// This is wrong for the same reason as $foo[bar] is wrong outside a string. 
// In other words, it will still work, but only because PHP first looks for a 
// constant named foo; an error of level E_NOTICE (undefined constant) will be 
// thrown. 
echo "This is wrong: {$arr[foo][3]}"; 

// Works. When using multi-dimensional arrays, always use braces around arrays 
// when inside of strings 
echo "This works: {$arr['foo'][3]}"; 

// Works. 
echo "This works: " . $arr['foo'][3]; 

echo "This works too: {$obj->values[3]->name}"; 

echo "This is the value of the var named $name: {${$name}}"; 

echo "This is the value of the var named by the return value of getName(): {${getName()}}"; 

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}"; 

// Won't work, outputs: This is the return value of getName(): {getName()} 
echo "This is the return value of getName(): {getName()}"; 
?> 

Patrz, że aktualizacja więcej przykładów.

Powiązane problemy