尝试在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
如何在字符串中实现?
感谢
答案 0 :(得分:5)
在双引号内调用类函数时,必须使用{}
。
echo "the name : {$example->getName()}";
答案 1 :(得分:2)
突破文本块:echo "the name : ".$example->getName();
答案 2 :(得分: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无法确定,所以你必须通过连接(不包括你的引号中的调用)来提供帮助,我个人更喜欢,或通过使用花括号明确分隔表达式
答案 3 :(得分:0)
这不适用于变量。 $example->getName()
是一种方法(不是可以假设的变量)。
像其他人一样使用建议:删除引号。