首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP中的字符串连接和类函数?

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

Stack Overflow用户
提问于 2010-11-10 10:57:13
回答 2查看 132关注 0票数 0

我在写一个简单的类。代码如下:

代码语言:javascript
复制
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 />";
    }
}

我初始化了类并调用了函数:

代码语言:javascript
复制
$test = new Book("Harry Potter", "2010-1-10");
$test->setAndDisplay("PHP For Beginners", "2010-2-10");

结果是:

代码语言:javascript
复制
"Title: PHP For Beginners published on 2010-2-10The new information is of the book"

它不应该是:

代码语言:javascript
复制
"The new information is of the book **Title: PHP For Beginners published on 2010-2-10**

有谁能解释一下吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-11-10 11:02:39

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

实际情况是,在setAndDisplay()echo中对displayBook()的调用发生在echo完成之前。

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

代码语言:javascript
复制
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传递参数比串联更快

票数 3
EN

Stack Overflow用户

发布于 2010-11-10 11:02:53

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

http://codepad.org/9pfqiRHu

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4140824

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档