2012-04-27 1 views
1

私は

echo "{$var1}someString" // here the variable is $var1 
echo "$var1someString" // here the variable is $var1someString 

質問なぜ{}を使用することですとの違いを作ることができますか?これは{}でのみ動作します。 ()では動作しません。 { }について特別なものは何ですか?

+2

私はそう思っています。 – Ahatius

+0

なぜそれは()のために動作しません何か私の頭を壊している、私はそれがブロック区切りであると思います、それはブロックを分離しますが、なぜ彼らは別の表現でもありますか? – nepsdotin

+0

構文はこのように動作するように定義されています。なぜ関数($ var){code}を作成するのか尋ねることはありません。それはちょうどこのように定義されています。 – Ahatius

答えて

1

あなたはそれを自分で留保しました。単にphpがこれに使用する構文だけです。 the documentationを引用する:

コンプレックス(カーリー)構文
は、それが文字列の外側に現れる同様に式を書き、その後、{と}でそれをラップします。 {はエスケープできないので、この構文は$が{の直後にある場合にのみ認識されます。

echo "{$var1}someString" 

あなたが見れば:

echo "$var1someString" 

リテラル{$

4

{}は、文字列内の変数を識別するために、そのように使用されている中括弧を取得するには、\ $ {使用しますPHPはおそらく$var1をエコーし​​たいと判断できません。そのすべてを変数名として扱います。

あなたは代わりに、変数を連結することができます:PHPの設計者は、{}を選択するという理由だけで、それは()のために動作しません

echo $var1 . "someString" 

1

stringのドキュメントによれば、中空部分は複雑な構文と呼ばれます。基本的には、string内で複雑な式を使うことができます。

ドキュメントから例:

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

をここ{}これらの内の変数は単純な文字列ので、PHP PICアップ変数の値の代わりに、単純な文字列として、ことを仮定しているないことを定義します。

関連する問題