我知道在php中您可以将变量嵌入变量中,例如:
1
| <? $var1 ="I\'m including {$var2} in this variable.."; ?> |
但是我想知道如何以及是否可以在变量中包含一个函数。
我知道我可以写:
1 2 3 4 5
| <?php
$var1 ="I\'m including";
$var1 .= somefunc();
$var1 =" in this variable..";
?> |
但是如果我有一个长变量用于输出,并且我不想每次都这样做,或者我想使用多个函数怎么办:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <?php
$var1 = <<<EOF
<html lang="en">
<head>
AAAHHHHH
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
There is alot of text and html here... but I want some functions!
-somefunc() doesn't work
-{somefunc()} doesn't work
-$somefunc() and {$somefunc()} doesn't work of course because a function needs to be a string
-more non-working: ${somefunc()}
</body>
</html>
EOF;
?> |
或者我想在代码负载中动态更改:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <?
function somefunc($stuff) {
$output ="my bold text {$stuff}.";
return $output;
}
$var1 = <<<EOF
<html lang="en">
<head>
AAAHHHHH
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
somefunc("is awesome!")
somefunc("is actually not so awesome..")
because somefunc("won\'t work due to my problem.")
</body>
</html>
EOF;
?> |
好吗?
自PHP5以来,通过在变量中包含要调用的函数名称来支持字符串内的函数调用:
1 2 3 4 5 6 7 8 9
| <?
function somefunc($stuff)
{
$output ="{$stuff}";
return $output;
}
$somefunc='somefunc';
echo"foo {$somefunc("bar")} baz";
?> |
将输出" foo bar baz"。
不过,我发现仅调用字符串之外的函数会更容易(这在PHP4中有效):
1 2 3
| <?
echo"foo" . somefunc("bar") ." baz";
?> |
或分配给一个临时变量:
1 2 3 4
| <?
$bar = somefunc("bar");
echo"foo {$bar} baz";
?> |
"bla bla bla".function("blub")." and on it goes"
进一步解释Jason W所说的话:
1 2 3 4 5 6
| I find it easier however (and this works in PHP4) to either just call the
function outside of the string:
<?
echo"foo" . somefunc("bar") ." baz";
?> |
您也可以直接在HTML中嵌入此函数调用,例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| <?
function get_date() {
$date = `date`;
return $date;
}
function page_title() {
$title ="Today's date is:". get_date() ."!";
echo"$title";
}
function page_body() {
$body ="Hello";
$body =", World!";
$body ="\
\
";
$body ="Today is:" . get_date() ."\
";
}
?>
<html>
<head>
<? page_title(); ?>
</head>
<body>
<? page_body(); ?>
</body>
</html> |