Reputation: 791
Recently I was reading php documentation and found interesting note in string section:
Functions, method calls, static class variables, and class constants inside {$} work since PHP 5. However, the value accessed 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.
See www.php.net/manual/en/language.types.string.php
It says, that I can't use curly syntax to get value returned by object's method call. Is it a mistake in manual or I misunderstood it, because I tried the following code and it works just fine:
<?php
class HelloWorld
{
public static function hello()
{
echo 'hello';
}
}
$a = new HelloWorld();
echo "{$a->hello()} world";
Upvotes: 5
Views: 221
Reputation: 95131
will not work for accessing the return values of functions or methods or the values of class constants or static class variables
$a->hello()
is not how to call a static method in PHP
and also not a constants or static class variables This is what they mean :
class HelloWorld {
const A = "A";// <---- You can not use it for this
public static $B = "B"; <---- or this
public static function hello() {
echo 'hello';
}
}
$a = new HelloWorld();
$A = "{HelloWorld::A} world"; <-------- Not Work
$B = "{HelloWorld::$B} world"; <-------- Not Work
$C = "{HelloWorld::hello()} world"; <-------- Not Work
If you now try
$A = "X"; // If you don't define this it would not work
$B = "Y" ; //<------------- -^
echo "{${HelloWorld::A}} world";
echo "{${HelloWorld::$B}} world";
Output
X world <--- returns X world instead of A
Y world <--- returns Y world instead of B
Upvotes: 3
Reputation: 7470
What I understand from that explanation is, the stress is on
(…) Using single curly braces…
So in the example there I think it wants to say:
echo "I'd like an {$beers::$ale}\n";
will not work hence single curly braces.
And that's why you should be using double curly braces, first of which will return the static output and the second of which will return the final output as in the example there:
echo "I'd like an {${beers::$ale}}\n";
^ ^ ^^
Upvotes: 0