How to print a constant in the middle of a string, without concatenating?

11

Is there any way to print a constant in the middle of a string , without using concatenation, how do you do with variables in PHP?

Example:

 $nome = 'wallace';
 echo "Meu nome é {$nome}";

For constants, I know I could print concatenating:

echo 'meu nome é' . NOME_USUARIO;

But I'd like to avoid concatenation because I find it inelegant.

Are there other possible ways to do this?

    
asked by anonymous 15.09.2015 / 22:53

3 answers

10

You can use the printf() function to print a formatted string and then pass the values to exchange or use commas in that case.

define('NOME_USUARIO', 'lol');

echo 'meu nome é ', NOME_USUARIO;
printf('meu nome é %s', NOME_USUARIO);
    
15.09.2015 / 22:56
6

A possible form would also be with something magical crazy that php allows: We can declare the value of the function constant - which serves to get the value of the constant - and save it in the variable . Then call it in the middle of the string you want.

See:

$c = 'constant';

define('nome', 'Wallace');

echo "Meu nome é {$c('nome')}";
    
15.09.2015 / 23:00
3

I do not think it's possible , at least until I read the documentation:

However, by doing some tests I realized that it is possible to force / cheat the syntax, such as @Wallace made in response , but the idea here is to create a variable that is an anonymous function, so you will not need the apostrophes , an example:

<?php
define('FOO', 'bar');

$constant = function ($nome) {
    return $nome;
};

echo "FOO = {$constant(FOO)}";

Another example catching "native" constants:

<?php
$constant = function ($nome) {
    return $nome;
};

echo "PHP_VERSION = {$constant(PHP_VERSION)}";

Example on ideone: link

If it does not exist as define() it will display exactly what was written:

<?php
$constant = function ($nome) {
    return $nome;
};

echo "BAZ = {$constant(BAZ)}"; //Exibe "BAZ = BAZ"
    
29.08.2018 / 21:51