21

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 {} inside a string but you can't do the simple thing that would make this method return the truth:

class c {
    const k = '12';
    public function s() {
        return "Twelve in decimal is {c::k}.";
    }
}

Is the right solution here to concatenate?

3
  • Since concatenation works, why wouldn't you just concatenate? Commented Jun 13, 2011 at 17:28
  • 15
    @evolve: the question is about the PHP language, not about what constitutes good code. Why I would or would not concatenate (if I had the choice) is beside the point. Commented Jun 13, 2011 at 18:45
  • 4
    In case anyone is wondering why you'd not want to concatenate; you might be using heredoc strings rather than double quoted strings. Both expand variables, but heredocs don't really play well with concatenation. Commented Oct 29, 2017 at 0:29

3 Answers 3

14

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.

Sign up to request clarification or add additional context in comments.

Comments

11

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";

1 Comment

That's precisely the part of the manual that I referenced in the OP and that got me a bit confused. But I think we agree on what it means.
6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.