【问题标题】:In PHP is it possible to use a function inside a variable在 PHP 中是否可以在变量中使用函数
【发布时间】:2010-09-08 19:01:34
【问题描述】:

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

嗯?

【问题讨论】:

  • $var1 = "我在这个变量中包含 {$var2}.."; ?> 为什么要在双引号中转义单引号? ;)

标签: php html variables function


【解决方案1】:

从 PHP5 开始,通过包含要调用的函数名称的变量来支持字符串中的函数调用:

<?
function somefunc($stuff)
{
    $output = "<b>{$stuff}</b>";
    return $output;
}
$somefunc='somefunc';
echo "foo {$somefunc("bar")} baz";
?>

将输出“foo &lt;b&gt;bar&lt;/b&gt; baz”。

我发现在字符串之外调用函数更容易(这在 PHP4 中有效):

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

或分配给一个临时变量:

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

【讨论】:

  • 我想这行得通,但我永远不会那样做。这是一种糟糕的做法。考虑一下代码的可读性等。六个月后回到你的代码,找出你的 HTML 标记中的所有函数调用。
  • 你永远不应该在你的视图中调用一个函数,除非像 htmlspecialchars 这样的转义函数(这是一个太长的函数名,因为它的目的,搞砸了,PHP)......
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    稍微扩展一下 Jason W 所说的内容:

    但是,我发现调用 字符串外的函数: 回声“富”。一些函数(“酒吧”)。 “巴兹”; ?>

    您也可以直接将此函数调用嵌入到您的 html 中,例如:

    函数获取日期(){ $date = `日期`; 返回$日期; } 功能页面标题(){ $title = "今天的日期是:"。 get_date() ."!"; 回声“$title”; } 功能页体(){ $body = "你好"; $body = ", 世界!"; $body = "\n
    \n"; $body = "今天是:" .获取日期()。 "\n"; } ?> page_body(); ?> 正文>
    猜你喜欢
    • 2011-11-23
    • 2011-10-28
    • 2017-09-10
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 2023-03-26
    相关资源
    最近更新 更多