tro*_*ter 10 html php variables function
我知道在php中你可以在变量中嵌入变量,比如:
<? $var1 = "I\'m including {$var2} in this variable.."; ?>
Run Code Online (Sandbox Code Playgroud)
但我想知道如何,以及是否可以在变量中包含一个函数.我知道我可以写:
<?php
$var1 = "I\'m including ";
$var1 .= somefunc();
$var1 = " in this variable..";
?>
Run Code Online (Sandbox Code Playgroud)
但是如果我有一个很长的变量输出,我不想每次都这样做,或者我想使用多个函数:
<?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;
?>
Run Code Online (Sandbox Code Playgroud)
或者我希望在代码加载中进行动态更改:
<?
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;
?>
Run Code Online (Sandbox Code Playgroud)
好?
Jas*_*red 25
PHP5之后支持字符串中的函数调用,它包含一个包含要调用的函数名称的变量:
<?
function somefunc($stuff)
{
$output = "<b>{$stuff}</b>";
return $output;
}
$somefunc='somefunc';
echo "foo {$somefunc("bar")} baz";
?>
Run Code Online (Sandbox Code Playgroud)
将输出" foo <b>bar</b> baz
".
我发现它更容易(并且这适用于PHP4)要么只是调用字符串之外的函数:
<?
echo "foo " . somefunc("bar") . " baz";
?>
Run Code Online (Sandbox Code Playgroud)
或分配给临时变量:
<?
$bar = somefunc("bar");
echo "foo {$bar} baz";
?>
Run Code Online (Sandbox Code Playgroud)