2012-04-23 7 views

risposta

4

Nel tuo esempio, non c'è differenza. Tuttavia, è utile quando l'espressione della variabile è più complessa, come una matrice con un indice di stringa. Ad esempio:

$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

Ah, vedo grazie molte. – Andy

4

Da PHP.net

Complex (riccio) sintassi

Questo non è chiamato complesso perché la sintassi è complessa, ma poiché consente l'uso di espressioni complesse ns.

Qualsiasi variabile scalare, elemento di matrice o proprietà di oggetto con una rappresentazione di stringa può essere inclusa tramite questa sintassi. È sufficiente scrivere l'espressione nello stesso modo in cui apparirebbe all'esterno della stringa e quindi racchiuderla in {e}. Poiché {non può essere sfuggito, questa sintassi sarà riconosciuta solo quando $ segue immediatamente il {. Utilizza {\ $ per per ottenere un valore letterale {$.

Esempio:

<?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()}"; 
?> 

Vedere la pagina per ulteriori esempi.

Problemi correlati