progamer
progamer

Reputation: 69

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?

Upvotes: 0

Views: 184

Answers (2)

Phil
Phil

Reputation: 164795

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

Upvotes: 3

Baylor Rae&#39;
Baylor Rae&#39;

Reputation: 4010

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

Upvotes: 1

Related Questions