Page 1 of 1
Any way to interpret function inside of <<< string
Posted: Tue Sep 13, 2011 5:54 pm
by elim
Code: Select all
$myFile = "cm123.mp3";
echo <<<FileRow
<A href={$myFile}>The Record</A>
FileRow;
Works well. But
Code: Select all
function myFile(){
return "cm123.mp3";
}
echo <<<FileRow
<A href={myFile()}>The Record</A>
FileRow;
Not working. Any trick to call the function inside of the string?
Thanks
Re: Any way to interpret function inside of <<< string
Posted: Tue Sep 13, 2011 6:30 pm
by AbraCadaver
It's easy if you don't use heredoc:
Code: Select all
echo '<A href='.myFile().'>The Record</A>';
Or if you must, it needs to be in a variable:
Code: Select all
$func = 'myfile';
echo <<<FileRow
<A href={$func()}>The Record</A>
FileRow;
But there's probably a better way to go about whatever it is that you're doing.
Re: Any way to interpret function inside of <<< string
Posted: Wed Sep 14, 2011 9:55 am
by Weirdan
You can call functions through a proxy object to satisfy the need for a variable:
Code: Select all
class FunctionCaller
{
public function __call($name, $args)
{
return call_user_func_array($name, $args);
}
}
$func = new FunctionCaller;
function myFile()
{
return 'zxc.jpg';
}
echo <<<EOF
blah blah blah {$func->myFile()} jfjfjfjfjf
EOF;
Re: Any way to interpret function inside of <<< string
Posted: Wed Sep 14, 2011 8:45 pm
by elim
Thanks a lot Weirdan! This exactly what I'm looking for. It can also pass variables
Code: Select all
$a = 1;
$b = 2;
function nm($a,$b){
return pow($a+$b, 2);
}
class FunctionCaller
{
public function __call($name, $args)
{
return call_user_func_array($name, $args);
}
}
$func = new FunctionCaller;
echo <<<MSTR
We'd like to know ($a + $b)^2 and it's {$func->nm($a,$b)} by my function.Very Nice!
MSTR;
The output is
We'd like to know (1 + 2)^2 and it's 9 by my function.Very Nice!
as expected!
The nice thing about this is to maintain the html template as it ought to be and
dynamically generate the content according to calculated data. Typically inside of a loop....