Include constant in string without concatenating

82,046

Solution 1

No.

With Strings, there is no way for PHP to tell string data apart from 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 either.

Manual on constants in PHP

Solution 2

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.

Solution 3

To use constants inside strings you can use the following method:

define( 'ANIMAL', 'turtles' ); 
$constant = 'constant';

echo "I like {$constant('ANIMAL')}";


How does this work?

You can use any string function name and arbitrary parameters

One can place any function name in a variable and call it with parameters inside a double-quoted string. Works with multiple parameters too.

$fn = 'substr';

echo "I like {$fn('turtles!', 0, -1)}";

Produces

I like turtles

Anonymous functions too

You can also use anonymous functions provided you're running PHP 5.3+.

$escape   = function ( $string ) {
    return htmlspecialchars( (string) $string, ENT_QUOTES, 'utf-8' );
};
$userText = "<script>alert('xss')</script>";
echo( "You entered {$escape( $userText )}" );

Produces properly escaped html as expected.

Callback arrays not allowed!

If by now you are under the impression that the function name can be any callable, that's not the case, as an array that returns true when passed to is_callable would cause a fatal error when used inside a string:

class Arr
{

    public static function get( $array, $key, $default = null )
    {
        return is_array( $array ) && array_key_exists( $key, $array ) 
            ? $array[$key] 
            : $default;
    }
}

$fn = array( 'Arr', 'get' );
var_dump( is_callable( $fn ) ); // outputs TRUE

// following line throws Fatal error "Function name must be a string"
echo( "asd {$fn( array( 1 ), 0 )}" ); 

Keep in mind

This practice is ill-advised, but sometimes results in much more readable code, so it's up to you - the possibility is there.

Solution 4

define( 'FOO', 'bar');  
$FOO = FOO;  
$string = "I am too lazy to concatenate $FOO in my string";

Solution 5

define('FOO', 'bar');
$constants = create_function('$a', 'return $a;');
echo "Hello, my name is {$constants(FOO)}";
Share:
82,046

Related videos on Youtube

Brian
Author by

Brian

Updated on October 24, 2021

Comments

  • Brian
    Brian over 2 years

    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";
    
    • Mikael Lindqvist
      Mikael Lindqvist about 7 years
      Intuition tells me that "This is my constant: {MY_CONSTANT}" should work. It doesn't. Just putting this here in case someone thinks the same as I.
  • raveren
    raveren about 12 years
    "function call can't be put into a string" yes it can: define('ANIMAL','turtles'); $constant='constant'; echo "I like {$constant('ANIMAL')}";
  • alephreish
    alephreish over 10 years
    This doesn't seem to work (even if you use uppercase consecutively) $GLOBALS is an associative array containing references to all variables.
  • hndcrftd
    hndcrftd about 10 years
    @Raveren you should have submitted your answer properly, not as a comment. I believe this answers OOP question (and mine) in the most efficient and elegant way. Thank you.
  • raveren
    raveren about 10 years
    I'm glad it helped, but there's been multiple answers added since my comment repeating what I said, there's no point in adding another one.
  • hndcrftd
    hndcrftd about 10 years
    @Raveren, while others offer indirect variations, unnecessarily creating functions, yours is the shortest and to the point solution that relies on variable functions, underrated and very infrequently used feature of PHP. Out of this whole thread I went with YOUR particular solution. I wish I could +1 it more than once.
  • raveren
    raveren about 10 years
    I provided an answer as requested, adding more info about why it works to make the answer more relevant to newcomers. stackoverflow.com/a/22407812/179104
  • designcise
    designcise almost 10 years
    @Raveren if you're going to do $constant='constant'; just to do this: echo "I like {$constant('ANIMAL')}"; .. isn't it better to just do: $animal = ANIMAL; echo "I like $animal"; instead?
  • raveren
    raveren almost 10 years
    I just pointed out it's possible, not commented on which way is better.
  • Beejor
    Beejor almost 9 years
    This is a great trick! Like the other answers, not really a big win over concatenation in terms of effort and readability, but nice to know. It's even sexier when you do something like $_ = create_function('$a','return $a;'); $s = "I like {$_(ANIMAL)}". Thetaiko's version removes the need for quotes, and an underscore is cute.
  • Beejor
    Beejor almost 9 years
    This is the one I use most, when I have a bunch of crazy SQL strings to compose. Also... passive-aggressive much? ;-)
  • Mnebuerquo
    Mnebuerquo about 8 years
    I could see this being useful for building a template engine, but it seems too sneaky to actually use.
  • Jeff Puckett
    Jeff Puckett almost 8 years
    this answer is wrong. the only way that this could possibly produce that output is if somewhere in your script you also have $db_user = 'root';
  • kta
    kta about 7 years
    I regard this as a good solution. In some cases, connect string won't work if use direct CONSTANT inside.
  • BrDaHa
    BrDaHa almost 7 years
    This one has the least amount of magic, at the expense of looking redundant
  • redreinard
    redreinard about 5 years
    You can just do $constant = 'constant'; instead of defining another function, and it would work identically since that function already exists.