Em PHP é possível usar uma função dentro de uma variável
Pergunta
Eu sei que no php você pode incorporar variáveis dentro de variáveis, como:
<? $var1 = "I\'m including {$var2} in this variable.."; ?>
Mas eu queria saber como e se era possível incluir uma função dentro de uma variável.Eu sei que poderia simplesmente escrever:
<?php
$var1 = "I\'m including ";
$var1 .= somefunc();
$var1 = " in this variable..";
?>
Mas e se eu tiver uma variável longa para saída e não quiser fazer isso sempre ou quiser usar várias funções:
<?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;
?>
Ou quero mudanças dinâmicas nessa carga de código:
<?
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;
?>
Bem?
Solução
Chamadas de função dentro de strings são suportadas desde o PHP5 por ter uma variável contendo o nome da função a ser chamada:
<?
function somefunc($stuff)
{
$output = "<b>{$stuff}</b>";
return $output;
}
$somefunc='somefunc';
echo "foo {$somefunc("bar")} baz";
?>
produzirá "foo <b>bar</b> baz
".
No entanto, acho mais fácil (e isso funciona no PHP4) apenas chamar a função fora da string:
<?
echo "foo " . somefunc("bar") . " baz";
?>
ou atribua a uma variável temporária:
<?
$bar = somefunc("bar");
echo "foo {$bar} baz";
?>
Outras dicas
"bla bla bla".function("blub")." and on it goes"
Expandindo um pouco o que Jason W disse:
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"; ?>
Você também pode incorporar esta chamada de função diretamente em seu HTML, como:
<? 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>