doc-en icon indicating copy to clipboard operation
doc-en copied to clipboard

Confusion about curly syntax statement

Open runbing opened this issue 3 years ago • 2 comments

From manual page: https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex


There is a note about "Complex (curly) syntax" on the manual page:

The value accessed from functions, method calls, static class variables, and class constants inside {$} will be interpreted as the name of a variable in the scope in which the string is defined. Using single curly braces ({}) will not work for accessing the return values of functions or methods or the values of class constants or static class variables.

I did some test to verify the last statement:

function test() { return 'a'; }
class Test {
    const A = 'a';
    static $b = 'b';
    function c() { return 'c'; }
}

echo "{test()}"; // Function in {} not working as expected
echo "{Test::A}"; // Constant in {} not working as expected
echo "{Test::$b}"; // Static property in {} not working as expected
echo "{(new Test())->a()}"; // Instantiate Test and call method c() inside {} not working as expected

$test = new Test(); // Instantiate A outside {}
echo "{$test->c()}"; // Calling the method c() inside {} is working which is not expected

The confusion is on word "methods" in the statement "Using single curly braces ({}) will not work for accessing the return values of functions or methods ...". As you can see from the test above, we can access the return value 'c' of method c(), which violates the statement.

Is there any problem with my understanding? Or the statement from manual is inaccurate on this matter?

runbing avatar Dec 13 '22 13:12 runbing

See the example below that note for what it is about (namely variable variables). I agree though, that it might make sense to clarify this. @Girgias, thoughts?

cmb69 avatar Dec 13 '22 14:12 cmb69

Makes sense, I suppose that's something to remember for my large string interpolation rewrite. Will have a go at it at some point this week.

Girgias avatar Dec 13 '22 15:12 Girgias