PHPでは変数内で関数を使用できますか
質問
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>
所属していません StackOverflow