OOP PHP - 课堂上的新手练习

时间:2013-07-02 16:35:42

标签: php oop

假设我们有两个非常基本的类: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()应该使用章节。

2 个答案:

答案 0 :(得分:2)

一本书基本上是一个章节列表。每章都有标题和文字。如何让图书对象负责建立索引?

<?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)

答案 1 :(得分: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;
    }
}

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