在PHP中可以在变量内使用函数

时间:2020-03-05 18:52:40  来源:igfitidea点击:

我知道在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 &lt;b> bar &lt;/ b> baz"。

但是,我发现只调用字符串之外的函数就更容易了(这在PHP4中有效):

<?
echo "foo " . somefunc("bar") . " baz";
?>

或者分配给一个临时变量:

<?
$bar = somefunc("bar");
echo "foo {$bar} baz";
?>

回答

`" bla bla bla" .function(" blub")。"随它去吧"

回答

扩展一下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>