En PHP es posible utilizar una función dentro de una variable
Pregunta
Sé que en php puedes incrustar variables dentro de variables, como:
<? $var1 = "I\'m including {$var2} in this variable.."; ?>
Pero me preguntaba cómo y si era posible incluir una función dentro de una variable.Sé que podría simplemente escribir:
<?php
$var1 = "I\'m including ";
$var1 .= somefunc();
$var1 = " in this variable..";
?>
Pero, ¿qué pasa si tengo una variable larga para la salida y no quiero hacer esto cada vez, o quiero usar múltiples funciones?
<?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;
?>
O quiero cambios dinámicos en esa 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;
?>
¿Bien?
Solución
Las llamadas a funciones dentro de cadenas son compatibles desde PHP5 al tener una variable que contiene el nombre de la función a llamar:
<?
function somefunc($stuff)
{
$output = "<b>{$stuff}</b>";
return $output;
}
$somefunc='somefunc';
echo "foo {$somefunc("bar")} baz";
?>
saldrá "foo <b>bar</b> baz
".
Sin embargo, me resulta más fácil (y esto funciona en PHP4) simplemente llamar a la función fuera de la cadena:
<?
echo "foo " . somefunc("bar") . " baz";
?>
o asignar a una variable temporal:
<?
$bar = somefunc("bar");
echo "foo {$bar} baz";
?>
Otros consejos
"bla bla bla".function("blub")." and on it goes"
Ampliando un poco lo que dijo 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"; ?>
También puedes simplemente incrustar esta llamada a función directamente en tu 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>