2013-07-02 30 views
-1

試圖使用我的類中的函數裏面的字符串中的回聲沒有工作,可能是因爲字符串「」,有沒有更好的方式來做到這一點?PHP中使用字符串「」前綴不工作的類功能

這是我的代碼:

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 

怎麼能這樣的字符串內可以實現嗎?

感謝

+1

請在這裏閱讀http://php.net/manual/en/language.types.string.php,尋找「複雜(捲曲)語法」。 – elclanrs

+0

如果你真的需要,這可能會奏效:'echo'這個名字:{$ example-> getName()}「;',但是Andy Gee的回答更好。 – 2013-07-02 08:01:51

回答

5

你必須使用{}當你調用雙引號中類的函數。

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

打出來的文本塊:echo "the name : ".$example->getName();

0

這是行不通的,因爲它與變量的作品。 $example->getName()是一種方法(不是可以假設的變量)。

像其他人一樣使用建議:放出引號。

2

您可以連擊:

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

由於CodeAngry指出的那樣,你可以將它傳遞給echo語言結構directy,太(旁路串聯):

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

或者使用大括號:

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

如果你不這樣做,在這種情況下,解析器不能確定什麼p字符串的藝術被視爲一種表達:你想:

'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無法確定,因此您必須通過連接(不包括引用中的調用)來伸出援助之手,我個人更喜歡,方法是使用大括號來明確地分隔表達式。

+0

**連接回聲弱**。你需要使用','。像'echo'的名稱:',$ example-> getName();'以防止一個無意義的連接。 – CodeAngry

+1

@CodeAngry:對,你是編輯答案 –