-1

尝试在 echo 中的字符串中使用我的类的函数不起作用,可能是因为字符串“”,有没有更好的方法呢?

这是我的代码:

class example{
    private $name = "Cool";

    function getName(){
        return $this->name;
    }
}


$example = new example();

//THIS WONT WORK 
echo "the name : $example->getName()";
//THIS WILL PRINT :
//the name : ()

//THIS WILL WORK
$name = $example->getName();
echo "the name : $name";
//THIS WILL PRINT :
//the name : Cool

如何在字符串内部实现这一点?

谢谢

4

4 回答 4

5

{}在双引号内调用类函数时必须使用。

echo "the name : {$example->getName()}";
于 2013-07-02T08:00:36.597 回答
2

打破文本块:echo "the name : ".$example->getName();

于 2013-07-02T08:00:59.500 回答
2

您可以连接:

echo 'the name: '.$example->getName();

正如 CodeAngry 指出的那样,您也可以直接将其传递给echo语言构造(绕过串联):

echo 'the name: ', $example->getName();

或者使用花括号:

echo "the name: {$example->getName()}";

如果你不这样做,在这种情况下,解析器无法确定字符串的哪一部分被视为表达式:你想要:

'the name {$example}->getName()';//where ->getName(); is a regular string constant

或者

'the name {$example->getName}()';//where ->getName is a property and (); is a regular string constant

还是暗示调用方法?PHP 无法确定,因此您必须通过连接(不包括引号中的调用)来提供帮助,这是我个人更喜欢的,或者通过使用花括号显式分隔表达式。

于 2013-07-02T08:01:16.057 回答
0

这不起作用,因为它适用于变量。$example->getName()是一种方法(不是假设的变量)。

像其他人建议的那样使用:去掉引号。

于 2013-07-02T08:01:06.110 回答