1

Possible Duplicate:
Include constant in string without concatenating

How can I get a constant to be evaluated in a string like variables are?

$foo = "like";
define('BAR', 'fish');

// None of these give me 'I like to eat fish on Tuesday.'
echo "I $foo to eat BAR on Tuesday.";
echo "I $foo to eat {BAR} on Tuesday.";
echo 'I $foo to eat BAR on Tuesday.';

// This works but is undesirable
echo 'I $foo to eat '.BAR.' on Tuesday.';
Community
  • 1
  • 1
Andrew
  • 8,363
  • 8
  • 43
  • 71

3 Answers3

2

The only way I know this'd works (which you may already be aware of) is by doing:

<?php
$foo = "like";
define('BAR', 'fish');
$constants = get_defined_constants();
echo "I $foo to eat {$constants['BAR']} on Tuesday.";
?>

which prints:

I like to eat fish on Tuesday.
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • I was aware, but thank you for the reassurance. I considered this option but it ended up reducing the code readability. – Andrew Feb 22 '11 at 22:01
  • Not only does it reduce code readability but it also prevents the IDE from detecting invalid constants in your string. – Ruan Mendes Apr 16 '11 at 00:10
1

As far as I know that isn't possibile. Check this answer here at SO, it contains useful workarounds if concatenation is so undesirable too you! Include constant in string without concatenating

Community
  • 1
  • 1
Damien Pirsy
  • 25,319
  • 8
  • 70
  • 77
-2

of course there is no way. And no need.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • -1 There's no explanation to your answer, just judgement. – Andrew Feb 22 '11 at 21:55
  • @Andrew there's no explanation to your question either. just "undesirable" judgement ;) – Your Common Sense Feb 22 '11 at 22:44
  • I'm surprised that someone with a 19k rep would post such a useless answer... Actually after looking at your profile, it seems your approach of being two steps ahead leads to a lot of condescending answers. – Ruan Mendes Apr 15 '11 at 23:08
  • @Juan did you happen to read the question? :) – Your Common Sense Apr 16 '11 at 00:01
  • I did. "How to have constants evaluated within strings". The reason I downvoted was that I actually find that it would be useful to be able to do "Select {MY_COLUMN_CONSTANT} from {MY_TABLE_CONSTANT} WHERE {OTHER_COLUMN} = :value" instead of harcoding constant names everywhere. Now I either have to do string concatenation, which makes it hard to read, or I have to copy the constants to local variables... – Ruan Mendes Apr 16 '11 at 00:08
  • Oh, I am blamed for some PHP feature, lol :) – Your Common Sense Apr 16 '11 at 00:14
  • Nobody is blaming you for the lack of this feature in PHP. Just not happy with your condescending comment/answer that there is no need for this. "There is no way" is accurate, but "no need" is your point of view, trying to see two steps ahead. – Ruan Mendes Apr 16 '11 at 00:20