PHP: Using a variable inside a double quotes

后端 未结 2 1694
长情又很酷
长情又很酷 2020-11-27 07:11

please check the following code.

$imagebaseurl = \'support/content_editor/uploads/$name\';

The $imagebaseurl is a variable th

相关标签:
2条回答
  • 2020-11-27 07:26
    $imagebaseurl = 'support/content_editor/uploads/' . $name;
    

    or

    $imagebaseurl = "support/content_editor/uploads/{$name}";
    

    Note that if you use double quotes, you can also write the above as:

    $imagebaseurl = "support/content_editor/uploads/$name";
    

    It's good though to get in the habit of using {$...} in double quotes instead of only $..., for times where you need to insert the variable in a string where it's not obvious to PHP which part is the variable and which part is the string.

    If you want the best performance, use string concatenation with single quotes.

    0 讨论(0)
  • 2020-11-27 07:40

    I couldn't disagree more with the previous post.

    I'd almost go as far to call it bad practice to use

    $varname = 'EXAMPLE';
    
    $fulltext = "This is an $varname";
    

    Its more maintainable, from my experience, to utilize a good friend of mine known as sprintf();

    define('CONST_NAME', 'This is an example of a better %s');
    define('EXAMPLE', sprintf(CONST_NAME, 'practice'));
    
    echo EXAMPLE;
    

    Why? The first one may seem more clear, but the second one is much more re-usable. I recommend utilizing sprintf over the php magic double quote nonesense which exists, literally, in NO other language.

    http://php.net/manual/en/function.sprintf.php

    This is also the practice used very similar to C#, and many other languages.

    See also: https://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx

    0 讨论(0)
提交回复
热议问题