我正在写一个简单的课程。这是代码:
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**
任何人都可以解释一下吗?
答案 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()
回应了字符串。当你试图追加或注入一个回声的东西时,它会被放在一开始。您必须用逗号.
替换点,
才能将其放置在您想要的位置。