像变量一样在字符串中扩展PHP函数

时间:2011-12-02 20:59:42

标签: php string function

在PHP中,我可以说

$noun = "bird";
$adjective = "warm;
echo <<<EOT
The $noun is very $adjective
EOT;

并输出

  

鸟很温暖

有没有办法用函数做到这一点?

function getNoun() { return "bird"; }
function getAdjective() { return "warm"; }
echo <<<EOT
The getNoun() is very getAdjective()
EOT;

和输出

  

鸟很温暖

4 个答案:

答案 0 :(得分:5)

您可以使用variable functions,虽然他们对此感到不满,因为他们与变量变量差别不大......

$a = 'getNoun';
$b = 'getAdjective';
echo <<<EOT
The {$a()} is very {$b()}
EOT;

答案 1 :(得分:2)

您可以在使用之前将其存储在变量中:

$noun = getNoun( );
$adj = getAdjective( );
echo <<<EOT
    The {$noun} is very {$adj}
EOT;

答案 2 :(得分:0)

echo "The ";
echo getNoun();
echo " is very ";
echo getVerb();

或者甚至(不是100%肯定):

echo "The " . getNoun() . " is very " . getVerb();

答案 3 :(得分:0)

这是一个使用变量函数的解决方案,尽管不完全是:

$noun=function($type){
    return $type;
};
$adjective=function($adj){
    return $adj;
};
echo "{$noun("Robin")} was very {$adjective("Warm")}";