Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constants inside quotes are not printed?

Tags:

php

This prints apple:

define("CONSTANT","apple");
echo CONSTANT;

But this doesn't:

echo "This is a constant: CONSTANT";

Why?

like image 209
Yeti Avatar asked May 30 '10 01:05

Yeti


3 Answers

Because "constants inside quotes are not printed". The correct form is:

echo "This is a constant: " . CONSTANT; 

The dot is the concatenation operator.

like image 174
Artefacto Avatar answered Sep 30 '22 09:09

Artefacto


define('QUICK', 'slow'); define('FOX', 'fox');  $K = 'strval';  echo "The {$K(QUICK)} brown {$K(FOX)} jumps over the lazy dog's {$K(BACK)}."; 
like image 40
gregjor Avatar answered Sep 30 '22 10:09

gregjor


If you want to include references to variables inside of strings you need to use special syntax. This feature is called string interpolation and is included in most scripting languages.

This page describes the feature in PHP. It appears that constants are not replaced during string interpolation in PHP, so the only way to get the behavior you want is to use the concatenation that Artefacto suggested.

In fact, I just found another post saying as much:

AFAIK, with static variables, one has the same 'problem' as with constants: no interpolation possible, just use temporary variables or concatenation.

like image 26
jasonmp85 Avatar answered Sep 30 '22 09:09

jasonmp85