开发者

String concatenation and class function in PHP?

I was writing a simple class. Here is the code:

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 />";
    }
}

And I initialized the class and called the function:

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

And the result is:

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

Shouldn't it be:

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

Can anyone explain?


The displayBook() method does not return a string (or anything for that matter) so you shouldn't really be using the result in a concatenation.

What's happening is the call to displayBook() in the echo in setAndDisplay() happens before the echo completes.

You should use different methods for direct output vs string generation, eg

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 />";
}

Edit: I'd seriously re-evaluate the need for your class to directly echo data. This is rarely a good idea.

Edit2: Passing parameters to echo is faster than concatenation


It's because displayBook() echos the string. And when you try to append or inject a function that echos something, it will get put at the beginning. You have to replace the dots . with commas ,for it to get placed where you want it.

http://codepad.org/9pfqiRHu

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜