Any way to interpret function inside of <<< string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
elim
Forum Newbie
Posts: 8
Joined: Tue Jun 24, 2008 10:19 am

Any way to interpret function inside of <<< string

Post 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
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Any way to interpret function inside of <<< string

Post 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.
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Any way to interpret function inside of <<< string

Post 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;
elim
Forum Newbie
Posts: 8
Joined: Tue Jun 24, 2008 10:19 am

Re: Any way to interpret function inside of <<< string

Post 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....
Post Reply