0

假设我们有两个非常基本的类:Chapter 和 Book。

PHP代码:

/**
 * Class Chapter
 */
class Chapter 
{
    private $title;

    public function __construct( $title )
    {
        $this->title = $title;
    }

    public function getTitle() 
    {
        return $this->title;
    }

    public function loadChapterTitle() 
    {
        $title = $this->getTitle();
        echo $title;

        return $title;
    }
}

/**
 * Class Book
 */
class Book
{
    //
}

使用示例:

$myTitleArray = array('first','second','third');
myBook = new Book($myTitleArray);

$myBook->loadBookIndex(); // echo: first, second, third

在 OOP 中,定义 Book 类及其 loadBookIndex() 方法的最优雅方式是什么?

编辑:仅出于 OO 教学目的... loadBookIndex() 应该使用章节。

4

2 回答 2

2

A book is essentially a list of chapters. Each chapter has a title and a text. What about letting the book object handling the responsibility of building an index?

<?php
class Chapter {

    public $title;
    public $text;

    public function __construct($title, $text) {
        $this->title = $title;
        $this->text = $text;    
    }
}

class Book {
    private $chapters;

    public function __construct() {
        $this->chapters = array();
    }

    public function addChapter(Chapter $chapter) {
        $this->chapters[] = $chapter;
    }   

    public function getIndex() {
        $index = array();

        foreach($this->chapters as $chapter) {
            $index[] = $chapter->title;
        }

        return $index;
    }    
}

// Usage
$book = new Book("foo");
$book->addChapter(new Chapter("Foreword", "Blabla"));
$book->addChapter(new Chapter("Introduction", "Blabla"));
$book->addChapter(new Chapter("Conclusion", "Blabla"));

$index = $book->getIndex(); // array(foreword, introduction, conclusion)
于 2013-07-02T16:50:08.817 回答
0

假设您无法更改用法/给出的内容,我会做这样的事情:

class Book {
    private $chapters = array();  // array to contain chapters

    public function __construct(array $chapterTitles) {
        // Create a new instance of class "Chapter" for each chapter and store
        // it in the $chapters array
        foreach ($chapterTitles as $title) {
            $this->chapters[] = new Chapter($title);
        }
    }

    public function loadBookIndex() {
        // Iterate over all chapters and load chapter information
        $index = array();
        foreach ($this->chapters as $chapter) {
            $index[] = $chapter->loadChapterTitle();
        }
        return $index;
    }
}

但是,尤其是那些“加载”方法的名称似乎具有误导性,因为这些方法实际上并没有加载任何东西。

于 2013-07-02T16:55:13.813 回答