문제

나는 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