Interpolate a constant (not variable) into 'heredoc'

后端 未结 6 1731
梦谈多话
梦谈多话 2020-12-29 01:47

Consider:

The value of my_const is {my_const}.

MYECHO; ?>
6条回答
  •  庸人自扰
    2020-12-29 02:11

    Here is an little trick to allow double-quoted strings and heredocs to contain arbitrary expressions in curly braces syntax, including constants and other function calls. It uses the fact that a function name can be assigned to a variable and then called within heredoc:

    = 5.3
        // Use a closure (anomynous function) like so:
        $_ = function ($val){return $val;};
    
        // Our test values
        define('abc', 'def');
        define('ghi', 3);
    
        $a = 1;
        $b = 2;
    
        function add($a, $b) { return $a+$b; }
    
        // Usage
        echo "b4 {$_(1+2)} after\n"; // Outputs 'b4 3 after'
        echo "b4 {$_(abc)} after\n"; // Outputs 'b4 def after'
        echo "b4 {$_(add($a, $b)+ghi*2)} after\n"; // Outputs 'b4 9 after'
        $text = <<

提交回复
热议问题