Class constant in a string in PHP

后端 未结 3 531
醉梦人生
醉梦人生 2021-02-07 02:57

My reading of the manual (the bit just before the section heading \"String access and modification by character\") is that you can do some fancy tricks with class constants and

相关标签:
3条回答
  • 2021-02-07 03:41

    Is the right solution here to concatenate?

    Yes. The extended curly syntax doesn't support it.

    Alternatively, you could export the list of constants to an array and use it (or export the constant to a single scalar variable name), but that's not really a good solution IMO.

    Note that constants are available, as you can do this:

    const k = 'foo';
    $foo = 'bar';
    echo "{${c::k}}"
    

    giving you bar, but that's not what you want.

    0 讨论(0)
  • 2021-02-07 03:46

    It's a little cryptic, but there is a note on this in the manual.

    Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

    The last sentence tells you it won't work so yes, concatenation is the way to go here.


    (modified) Example of above paragraph:

    <?php
    class beers {
        const softdrink = 'rootbeer';
    }
    
    $rootbeer = 'A & W';
    
    // This works; outputs: I'd like an A & W
    echo "I'd like an {${beers::softdrink}}\n";
    
    // This won't work; outputs: I'd like an {beers::softdrink}
    echo "I'd like an {beers::softdrink}\n";
    
    0 讨论(0)
  • 2021-02-07 03:49

    The curly syntax only works for 'variable expressions'. And you need anything that you can access with {$.

    Oh, there's only that workaround:

        $c = "constant";
        return "Twelve in decimal is {$c('c::k')}.";
    

    Which is obviously not much shorter or more readable than just using string concatenation here.

    0 讨论(0)
提交回复
热议问题