我知道在php中你可以在变量中嵌入变量,比如:
<? $var1 = "I\'m including {$var2} in this variable.."; ?>
但我想知道如何,以及是否可以在变量中包含一个函数。 我知道我可以写:
<?php
$var1 = "I\'m including ";
$var1 .= somefunc();
$var1 = " in this variable..";
?>
但是如果输出有一个很长的变量,我不想每次都这样做,或者我想使用多个函数:
<?php
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
There is <b>alot</b> of text and html here... but I want some <i>functions</i>!
-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;
?>
或者我希望在代码加载中进行动态更改:
<?
function somefunc($stuff) {
$output = "my bold text <b>{$stuff}</b>.";
return $output;
}
$var1 = <<<EOF
<html lang="en">
<head>
<title>AAAHHHHH</title>
<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;
?>
好?
答案 0 :(得分:25)
PHP5之后支持字符串中的函数调用,它包含一个包含要调用的函数名称的变量:
<?
function somefunc($stuff)
{
$output = "<b>{$stuff}</b>";
return $output;
}
$somefunc='somefunc';
echo "foo {$somefunc("bar")} baz";
?>
将输出“foo <b>bar</b> baz
”。
我发现它更容易(并且这适用于PHP4)要么只是调用字符串之外的函数:
<?
echo "foo " . somefunc("bar") . " baz";
?>
或分配给临时变量:
<?
$bar = somefunc("bar");
echo "foo {$bar} baz";
?>
答案 1 :(得分:2)
"bla bla bla".function("blub")." and on it goes"
答案 2 :(得分:-1)
扩大Jason W所说的内容:
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中嵌入此函数调用,例如:
<? 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 = "\n
\n"; $body = "Today is: " . get_date() . "\n"; } ?> <html> <head> <title><? page_title(); ?></title> </head> <body> <? page_body(); ?> </body> </html>