我正在運行PHP 5.3.0。我發現,只有當表達式的第一個字符是$
時,捲曲字符串語法才起作用。有沒有辦法包含其他類型的表達式(函數調用等)?PHP卷積字符串語法問題
簡單的例子:
<?php
$x = '05';
echo "{$x}"; // works as expected
echo "{intval($x)}"; // hoped for "5", got "{intval(05)}"
我正在運行PHP 5.3.0。我發現,只有當表達式的第一個字符是$
時,捲曲字符串語法才起作用。有沒有辦法包含其他類型的表達式(函數調用等)?PHP卷積字符串語法問題
簡單的例子:
<?php
$x = '05';
echo "{$x}"; // works as expected
echo "{intval($x)}"; // hoped for "5", got "{intval(05)}"
號只有各種形式的變量可以使用可變的取代基取代。
看看這個鏈接的代碼LINK
例,
Similarly, you can also have an array index or an object property parsed. With array indices, the closing square bracket (]) marks the end of the index. For object properties the same rules apply as to simple variables, though with object properties there doesn't exist a trick like the one with variables.
<?php
// These examples are specific to using arrays inside of strings.
// When outside of a string, always quote your array string keys
// and do not use {braces} when outside of strings either.
// Let's show all errors
error_reporting(E_ALL);
$fruits = array('strawberry' => 'red', 'banana' => 'yellow');
// Works but note that this works differently outside string-quotes
echo "A banana is $fruits[banana].";
// Works
echo "A banana is {$fruits['banana']}.";
// Works but PHP looks for a constant named banana first
// as described below.
echo "A banana is {$fruits[banana]}.";
// Won't work, use braces. This results in a parse error.
echo "A banana is $fruits['banana'].";
// Works
echo "A banana is " . $fruits['banana'] . ".";
// Works
echo "This square is $square->width meters broad.";
// Won't work. For a solution, see the complex syntax.
echo "This square is $square->width00 centimeters broad.";
?>
有不同的東西,你可以用大括號實現,但它是有限的,這取決於你如何使用它。
<?php
$x = '05';
echo "{$x}";
$a = 'intval';
echo "{$a($x)}";
?>
聰明......如果我對氣味不過敏,我會使用它:) – zildjohn01 2010-05-06 16:27:22
<?php
class Foo
{
public function __construct() {
$this->{chr(8)} = "Hello World!";
}
}
var_dump(new Foo());
一般來說,你不需要括號周圍變量,除非你需要強制PHP對待的東西作爲一個變量,在其正常的解析規則,否則可能不會。最大的是多維數組。 PHP的解析器對於決定什麼是變量和什麼不是,所以需要大括號來強制PHP查看剩餘的數組元素引用:
<?php
$arr = array(
'a' => array(
'b' => 'c'
),
);
print("$arr[a][b]"); // outputs: Array[b]
print("{$arr[a][b]}"); // outputs: (nothing), there's no constants 'a' or 'b' defined
print("{$arr['a']['b']}"); // ouputs: c
yes。但爲什麼?生產美味的意大利麪條? – 2010-05-06 16:22:45