我在写一个简单的类。代码如下:
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**有谁能解释一下吗?
发布于 2010-11-10 11:02:39
displayBook()方法不返回字符串(或任何字符串),因此您不应该真正在串联中使用结果。
实际情况是,在setAndDisplay()的echo中对displayBook()的调用发生在echo完成之前。
你应该使用不同的方法进行直接输出和字符串生成,例如
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传递参数比串联更快
发布于 2010-11-10 11:02:53
这是因为displayBook()回显了字符串。当你试图追加或注入一个回显的函数时,它会被放在开头。您必须将点.替换为逗号,,才能将其放置在您想要的位置。
http://codepad.org/9pfqiRHu
https://stackoverflow.com/questions/4140824
复制相似问题