views:

354

answers:

5

Is there a way in PHP to include a constant in a string without concatenating?

+6  A: 

No.

In Strings, there is no way for PHP to tell apart string data and constant identifiers. This goes for any of the string formats in PHP including heredoc.

constant() is an alternative way to get hold of a constant, but a function call can't be put into a string without concatenation, neither.

Manual on constants in PHP

Pekka
+1 anyway as it undoubtedly the right answer. First I wanted to write the same as you, but after reading yours, I thought I have to present something different ;)
Felix Kling
@Felix I hear ya, nothing worse than boredom! :)
Pekka
+1 from me too, cause this is the correct one.. What other should a programmer at 00:33, than hacking and bypassing rules ? :-D
Juraj Blahunka
Hehe! But a well deserved +1 for everyone for creativity. :)
Pekka
+3  A: 

Yes it is (in some way ;) ):

define('FOO', 'bar');

$test_string = sprintf('This is a %s test string', FOO);

This is probably not what you were aiming for, but I think, technically this is not concatenation but a substitution and from this assumption, it includes a constant in a string without concatenating.

Felix Kling
Cheater! ;) -----
Pekka
@Pekka: I know :-D (just this time... ;) )
Felix Kling
:) @juraj.blahunka's approach is even more sneaky. It answers the question by the letter, but not its spirit. :)
Pekka
:-D there is always a way
Juraj Blahunka
@blahunka: nice motto. We probably use it daily
Alfabravo
+1  A: 

If you really want to echo constant without concatenation here is solution:

define('MY_CONST', 300);
echo 'here: ', MY_CONST, ' is a number';

note: in this example echo takes a number of parameters (look at the commas), so it isn't real concatenation

Echo behaves as a function, it takes more parameters, it is more efficient than concatenation, because it doesn't have to concatenate and then echo, it just echoes everything without the need of creating new String concatenated object :))

EDIT

Also if you consider concatenating strings, passings strings as parameters or writing whole strings with " , The , (comma version) is always fastest, next goes . (concatenation with ' single quotes) and the slowest string building method is using double quotes ", because expressions written this way have to be evaluated against declared variables and functions..

Juraj Blahunka
+1  A: 

You could do:

define( 'FOO', 'bar' );

$constants = get_defined_constants();
$constants = $constants[ 'user' ];

echo "Hello, my name is {$constants['FOO']}";
Simon
A: 
define('FOO', 'bar');
$constants = create_function('$a', 'return $a;');
echo "Hello, my name is {$constants(FOO)}";
thetaiko