Include constant in string without concatenating

2020-01-24 02:40发布

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

define('MY_CONSTANT', 42);

echo "This is my constant: MY_CONSTANT";

12条回答
▲ chillily
2楼-- · 2020-01-24 02:52

You could do:

define( 'FOO', 'bar' );

$constants = get_defined_constants(true); // the true argument categorizes the constants
$constants = $constants[ 'user' ]; // this gets only user-defined constants

echo "Hello, my name is {$constants['FOO']}";
查看更多
We Are One
3楼-- · 2020-01-24 02:55

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.

查看更多
趁早两清
4楼-- · 2020-01-24 02:55
define('FOO', 'bar');
$constants = create_function('$a', 'return $a;');
echo "Hello, my name is {$constants(FOO)}";
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-01-24 02:58

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..

查看更多
太酷不给撩
6楼-- · 2020-01-24 03:00

The easiest way is

define('MY_CONSTANT', 42);

$my_constant = MY_CONSTANT;
echo "This is my constant: $my_constant";

Another way using (s)printf

define('MY_CONSTANT', 42);

// Note that %d is for numeric values. Use %s when constant is a string    
printf('This is my constant: %d', MY_CONSTANT);

// Or if you want to use the string.

$my_string = sprintf('This is my constant: %d', MY_CONSTANT);
echo $my_string;
查看更多
SAY GOODBYE
7楼-- · 2020-01-24 03:02

I believe this answers the OP's original question. The only thing is the globals index key seems to only work as lower case.

define('DB_USER','root');
echo "DB_USER=$GLOBALS[db_user]";

Output:

DB_USER=root
查看更多
登录 后发表回答