php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #71927 string interpolation with ${}
Submitted: 2016-03-31 01:27 UTC Modified: 2016-03-31 06:39 UTC
Votes:2
Avg. Score:4.0 ± 1.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: 1783946138 at qq dot com Assigned:
Status: Open Package: Scripting Engine problem
PHP Version: 7.0.5 OS:
Private report: No CVE-ID: None
 [2016-03-31 01:27 UTC] 1783946138 at qq dot com
Description:
------------
The unstable result to use "{}" in string interpolation.It's just because useing space.



Test script:
---------------
error_reporting(E_ALL);

define('great','my');
$great='fantastic';
$my='my value';
echo "This is ${great }<br/>";//output:my value
echo "This is ${ great}<br/>";//output:my value
echo "This is ${ great }<br/>";//output:my value
echo "This is ${great}<br/>";//output:fantastic

Expected result:
----------------
none

Actual result:
--------------
none

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-03-31 06:39 UTC] requinix@php.net
-Summary: string interpolation +Summary: string interpolation with ${} -Package: PHP Language Specification +Package: Scripting Engine problem -Operating System: windows +Operating System: -PHP Version: 5.5.33 +PHP Version: 7.0.5
 [2016-03-31 06:39 UTC] requinix@php.net
Huh. https://3v4l.org/jQXFc

I think this is intentional. Or at least a side-effect of intentional design.

${expression} basically has two behaviors:
1. If "expression" is a valid variable name then the value of $expression (or empty string if not defined) is interpolated into the string.
2. If "expression" is not a valid variable name then expression is evaluated and the result is expected to be the name of a variable which can be interpolated.

The first three variations are not valid variable names so the expressions "great ", " great", and " great " are evaluated using the constant and the result is effectively ${my} = "my value".
The fourth variation is a valid variable name and so is interpolated as $great = "fantastic".

This is a little different from how the same syntax works outside of strings: the "expression" is *always* treated as an expression. https://3v4l.org/IjhcH

http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex

I feel like that section could go into more detail about how the {$} and ${} syntaxes work and about what all is and is not allowed with each.
 [2023-05-16 10:20 UTC] autoupdatedaily at gmail dot com
Auto Advice Update are sharing latest news about auto, maintaince, car, bus, bilkes, electric bikes and scooters etc. More info to visit: (https://autoadviceupdate.com)github.com
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Dec 21 11:01:30 2024 UTC