2010-11-10 40 views
0

我正在寫一個簡單的課。下面是代碼:PHP中的字符串連接和類函數?

class Book{ 
    var $title; 
    var $publishedDate; 

    function Book($title, $publishedDate){ 
     $this->title = $title; 
     $this->publishedDate = $publishedDate; 
    } 

    function displayBook(){ 
     echo "Title: " . $this->title . " published on " . $this->publishedDate . ""; 
    } 

    function setAndDisplay($newTitle, $newDate){ 
     $this->title = $newTitle; 
     $this->publishedDate = $newDate; 
     echo "The new information is of the book <b>" . $this->displayBook() . "</b><br />"; 
    } 
} 

我初始化類和調用的函數:

$test = new Book("Harry Potter", "2010-1-10"); 
$test->setAndDisplay("PHP For Beginners", "2010-2-10"); 

,其結果是:

"Title: PHP For Beginners published on 2010-2-10The new information is of the book" 

它不應該是:

"The new information is of the book **Title: PHP For Beginners published on 2010-2-10** 

任何人都可以解釋一下嗎?

回答

3

displayBook()方法不返回一個字符串(或任何與此有關的),所以你真不該使用結果的串聯。

發生了什麼事是setAndDisplay()echo調用displayBook()發生之前echo完成。

,您應該使用不同的方法來直接輸出VS串產生,如

public function getBook() 
{ 
    return sprintf('Title: %s published on %s', 
        $this->title, 
        $this->publishedDate); 
} 

public function displayBook() 
{ 
    echo $this->getBook(); 
} 

public function setAndDisplay($newTitle, $newDate) 
{ 
    $this->title = $newTitle; 
    $this->publishedDate = $newDate; 
    echo "The new information is of the book <b>", $this->getBook(), "</b><br />"; 
} 

編輯:我會認真地重新評估你的類直接echo數據的需要。這很少是一個好主意。

EDIT2:將參數傳遞給echo比串聯

+0

嗯......我明白了。所以我必須先儲存一個變量,然後再進行連接? – progamer 2010-11-10 03:07:27

+0

@ wordpress_newbie - 對不起,我今天是打字員。看到我的編輯 – Phil 2010-11-10 03:11:55

+0

嘿謝謝。現在我明白了:D – progamer 2010-11-10 03:12:58

1

它的速度更快,因爲displayBook()回聲的字符串。而當你試圖追加或注入一個迴響某個東西的函數時,它將會被放在開頭。您必須用逗號,替換點.,以便將其放置在您想要的位置。

http://codepad.org/9pfqiRHu

+0

哦..它的作品,如果我用逗號取代笑 – progamer 2010-11-10 03:10:27

+0

這裏的原因 - http://www.php.net/manual/en/function.echo.php#78898 – Phil 2010-11-10 03:13:58