PHP中的字符串连接和类函数?

时间:2010-11-10 02:57:13

标签: php class string-concatenation

我正在写一个简单的课程。这是代码:

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**

任何人都可以解释一下吗?

2 个答案:

答案 0 :(得分:3)

displayBook()方法不返回字符串(或任何相关内容),因此您不应该在串联中使用结果。

在<{1}} 完成之前,displayBook() echo setAndDisplay()echo的调用发生了 {/ 1>}。

您应该使用不同的方法进行直接输出和字符串生成,例如

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比连接更快

答案 1 :(得分:1)

这是因为displayBook()回应了字符串。当你试图追加或注入一个回声的东西时,它会被放在一开始。您必须用逗号.替换点,才能将其放置在您想要的位置。

http://codepad.org/9pfqiRHu