5

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";
4

2 回答 2

3

PHP DOC 说

不适用于访问函数或方法的返回值或类常量或静态类变量的值

$a->hello()不是如何调用静态方法,PHP也不是常量或静态类变量这就是它们的意思:

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

如果你现在尝试

$A = "X";    // If you don't define this it would not work
$B = "Y" ;   //<------------- -^

echo "{${HelloWorld::A}} world";  
echo "{${HelloWorld::$B}} world"; 

输出

X world           <--- returns X world instead of A
Y world           <--- returns Y world instead of B
于 2012-10-20T23:09:23.043 回答
0

我从那个解释中了解到,压力在

(...) 使用单个花括号...</p>

所以在这个例子中,我认为它想说:

echo "I'd like an {$beers::$ale}\n";将不起作用,因此单个花括号。
这就是为什么你应该使用双花括号,第一个将返回静态输出,第二个将返回最终输出,如示例中所示:

echo "I'd like an {${beers::$ale}}\n";
                  ^ ^           ^^
于 2012-10-20T23:09:18.503 回答