quoting constants in php: "this is a MY_CONSTANT"

Viewed 10782

I want to use a constant in PHP, but I also want to put it inside double quotes like a variable. Is this at all possible?

define("TESTER", "World!");
echo "Hello, TESTER";

obviously outputs "Hello, TESTER", but what I really want is something like:

$tester = "World!";
echo "Hello, $tester";

outputs "Hello, World!".

7 Answers

Posting for anyone who might find it useful, something like this will work:

<?php
// example code
define('AAA', '30V');
$constant = 'constant';
echo "{$constant('AAA')}"; //Echoes 30V

Trust me, neither I believed something like this was possible, but it is! Try it in tehplayground.com and see for yourself.

Credit goes to whoever though of it, and to my colleague who found it (I think he did in stackoveflow).

Tested in: PHP 5.6, 7.4.27, 8.1

Alternatively, do

"this is " . MY_CONSTANT

or

"this is " . constant("MY_CONSTANT");
Related