我知道在 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;
?>

出色地?

有帮助吗?

解决方案

自 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";
?>

其他提示

"bla bla bla".function("blub")." and on it goes"

扩展一下 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>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top