違いがわかります
echo "{$var1}someString" // here the variable is $var1
echo "$var1someString" // here the variable is $var1someString
問題は、なぜ使用するの{}
かということです。でのみ機能し{}
ます。では動作しません()
。何がそんなに特別なの{ }
ですか?
The curly braces {}
are used in that way to identify variables within strings:
echo "{$var1}someString"
If you look at:
echo "$var1someString"
PHP can't possibly determine that you wanted to echo $var1
, it's going to take all of it as the variable name.
You could concatenate your variables instead:
echo $var1 . "someString"
It doesn't work for ()
simply because the PHP designers choose {}
.
あなたはそれを自分で説明しました。これは単に php がこれに使用する構文です - それ以上のものはありません。ドキュメントを引用するには:
複雑な (カーリー) 構文
文字列の外側に表示されるのと同じ方法で式を記述し、 { と } で囲みます。{ はエスケープできないため、この構文は { の直後に $ が続く場合にのみ認識されます。{\$ を使用してリテラル {$ を取得します
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()}";
?>
ここで{}
は、これらの変数が単純な文字列ではないことを定義しているため、php は変数値を単純な文字列と見なすのではなく、その変数値を取得します。