代码之家  ›  专栏  ›  技术社区  ›  aland

如何使用复杂(卷曲)语法的常量?

  •  5
  • aland  · 技术社区  · 14 年前

    我很惊讶地看到,下面的工作并不像预期的那样。

    define('CONST_TEST','Some string');
    echo "What is the value of {CONST_TEST} going to be?";
    

    输出:{CONST\u TEST}的值是多少?

    是的,我知道我可以

    echo "What is the value of ".CONST_TEST." going to be?";
    

    但我不希望合并字符串,与其说是为了性能,不如说是为了可读性。

    4 回复  |  直到 14 年前
        1
  •  6
  •   Sarfraz    14 年前

    不,这是不可能的,因为php会考虑 CONST_TEST 只是 在单引号/双引号内。你必须使用 为了这个。

    echo "What is the value of ".CONST_TEST." going to be?";
    
        2
  •  2
  •   bcosca    14 年前

    我不明白你为什么要大惊小怪,但你总是可以做到:

    define('CONST_TEST','Some string');
    $def=CONST_TEST;
    echo "What is the value of $def going to be?";
    
        3
  •  1
  •   Ruan Mendes    14 年前

    define('CONST_TEST','Some string');
    printf("What is the value of %s going to be?", CONST_TEST);
    
        4
  •  1
  •   Hasta Dhana    5 年前

    如果您非常想要这个特性,可以使用反射编写一段代码,查找所有常量及其值。然后将它们放入一个变量中,如 $CONSTANTS['CONSTANT_NAME']... $CONSTANTS

    所以使用它看起来像:

    $CONSTANTS = new constant_collection();
    
    //this bit would normally be automatically populate using reflection to find all the constants... but just for demo purposes, here is what would and wouldn't be allowed.
    $CONSTANTS['PI'] = 3.14;
    $CONSTANTS['PI'] = 4.34; //triggers an error
    unset($CONSTANTS['PI']); //triggers an error
    foreach ($CONSTANTS as $name=>$value) {
        .... only if the correct interface methods are implemented to allow this
    }
    print count($CONSTANTS); //only if the countable interface is implemented to allow this
    
    print "PI is {$CONSTANTS['PI']}"; //works fine :D
    

    $C 而不是 $常量 ;)

    希望有帮助,斯科特

    推荐文章