phpstringclasssyntaxclass-constants

Why the class constant value is getting evaluated in one statement and not in other?


I'm using PHP 7.2.6

I've tried following program :

<?php

  class beers {
    const softdrink = 'rootbeer';
  }

  $rootbeer = 'A & W';

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

  echo "I'd like an {beers::softdrink}\n"; //Output : I'd like an {beers::softdrink} 

?>

In the above statement, in first echo statement value of the class constant softdrink is evaluated as the string 'rootbeer' which in turn a variable name which contains the string 'A & W'. The value 'A & W' gets printed.

In second echo statement I only want to show the value present in the class constant softdrink which is the string 'rootbeer'.

But I'm not able to do it. Please help me in this regard.

P.S. : Please don't ask me to achieve the output using string concatenation. I want to achieve the output only by using the class constant within a double quotes string.


Solution

  • Afaik this is not possible. The whole "variable parsing" (extended curly syntax) in strings is done base on variables. Variables always start with a $ sign, so not starting with a $ does not seem to work. (i.e. Everything which is not (part of) a variable cannot be used.).

    Simplified example (which wont work):

    const TEST = 'A & W';
    echo "I'd like an {TEST}\n";
    

    Same for function calls (which also do not work directly)

    $test = '   A & W   ';
    echo "I'd like an {trim($test)}\n";
    

    Only in "sub" curly braces the desired output can be used, but it has to be parsed as a variable again which makes it impossible (at this point).

    Does work:

    $AW = 'A & W';
    $test = '   AW   ';
    echo "I'd like an {${trim($test)}}\n";
    

    Edit:

    If you truly WANT to output a (class) constant inside a complex curly brace expression:

    class beers {
        const softdrink = 'rootbeer';
    }
    
    function foobar($test) {
        $GLOBALS[$test] = $test;
        return $test;
    }
    
    echo "I'd like an {${foobar(beers::softdrink)}}\n";
    

    This is far from what I would recommend to do!!!