In PHP è possibile utilizzare una funzione all'interno di una variabile
Domanda
So che in php puoi incorporare variabili all'interno di variabili, come:
<? $var1 = "I\'m including {$var2} in this variable.."; ?>
Ma mi chiedevo come e se fosse possibile includere una funzione all'interno di una variabile.So che potrei semplicemente scrivere:
<?php
$var1 = "I\'m including ";
$var1 .= somefunc();
$var1 = " in this variable..";
?>
Ma cosa succede se ho una variabile lunga per l'output e non voglio farlo ogni volta o voglio utilizzare più funzioni:
<?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;
?>
Oppure voglio modifiche dinamiche in quel carico di codice:
<?
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;
?>
BENE?
Soluzione
Le chiamate di funzioni all'interno delle stringhe sono supportate a partire da PHP5 avendo una variabile contenente il nome della funzione da chiamare:
<?
function somefunc($stuff)
{
$output = "<b>{$stuff}</b>";
return $output;
}
$somefunc='somefunc';
echo "foo {$somefunc("bar")} baz";
?>
emetterà "foo <b>bar</b> baz
".
Trovo tuttavia più semplice (e funziona in PHP4) semplicemente chiamare la funzione all'esterno della stringa:
<?
echo "foo " . somefunc("bar") . " baz";
?>
o assegnare a una variabile temporanea:
<?
$bar = somefunc("bar");
echo "foo {$bar} baz";
?>
Altri suggerimenti
"bla bla bla".function("blub")." and on it goes"
Espandendo un po' ciò che ha detto 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"; ?>
Puoi anche incorporare questa chiamata di funzione direttamente nel tuo codice HTML, come:
<? 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>