En PHP est-il possible d'utiliser une fonction à l'intérieur d'une variable
Question
Je sais qu'en php, vous pouvez intégrer des variables à l'intérieur de variables, comme :
<? $var1 = "I\'m including {$var2} in this variable.."; ?>
Mais je me demandais comment et s'il était possible d'inclure une fonction dans une variable.Je sais que je pourrais simplement écrire :
<?php
$var1 = "I\'m including ";
$var1 .= somefunc();
$var1 = " in this variable..";
?>
Mais que se passe-t-il si j'ai une longue variable à afficher et que je ne veux pas le faire à chaque fois, ou si je souhaite utiliser plusieurs fonctions :
<?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 je veux des changements dynamiques dans cette charge de code :
<?
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?
La solution
Les appels de fonctions au sein de chaînes sont supportés depuis PHP5 en ayant une variable contenant le nom de la fonction à appeler :
<?
function somefunc($stuff)
{
$output = "<b>{$stuff}</b>";
return $output;
}
$somefunc='somefunc';
echo "foo {$somefunc("bar")} baz";
?>
affichera "foo <b>bar</b> baz
".
Je trouve cependant plus facile (et cela fonctionne en PHP4) d'appeler simplement la fonction en dehors de la chaîne :
<?
echo "foo " . somefunc("bar") . " baz";
?>
ou affecter à une variable temporaire :
<?
$bar = somefunc("bar");
echo "foo {$bar} baz";
?>
Autres conseils
"bla bla bla".function("blub")." and on it goes"
Développant un peu ce que Jason W a dit :
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"; ?>
Vous pouvez également simplement intégrer cet appel de fonction directement dans votre code HTML, comme :
<? 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>