使用双引号中的复杂(卷曲)语法解析常量

时间:2017-11-27 11:15:10

标签: php

我无法在双引号中使用复杂(卷曲)语法的概念 -

class beers {
    const softdrink = 'rootbeer';
    public static $ale = 'ipa';
}

define('TEST_DATA','test');
$test='hello';

$rootbeer = 'A & W';
$ipa = 'Alexander Keith\'s';

//This works; outputs: I'd like an A & W
echo "I'd like an ${beers::softdrink}\n";

//This works too; outputs: I'd like an Alexander Keith's
echo "I'd like an ${beers::$ale}\n";

//but this not work
echo "I'd like an ${TEST_DATA}\n";

${TEST_DATA}在常量的情况下不起作用,但是在类常量${beers::softdrink}的情况下它的工作。

1 个答案:

答案 0 :(得分:0)

这可以通过小黑客来实现

<?php 
class beers {
    const softdrink = 'rootbeer';
    public static $ale = 'ipa';
}

// hack declaration
function _expr($v) { return $v; }
$_expr = '_expr';

define('TEST_DATA','test');
$test='hello';


$rootbeer = 'A & W';
$ipa = 'Alexander Keith\'s';

//This works; outputs: I'd like an A & W
echo "I'd like an ${beers::softdrink}\n";

//This works too; outputs: I'd like an Alexander Keith's
echo "I'd like an ${beers::$ale}\n";

//this should work
echo "I'd like an ${$_expr(TEST_DATA)} \n";

//This works; outputs: I'd like an A & W
echo "I'd like an ${$_expr(beers::softdrink)}\n";

?>

应该打印以下

我想要A&amp; w ^

我想要Alexander Keith的

我想要一个我喜欢的问候

我想要A&amp; w ^

了解更多详情 should have basic support