【发布时间】:2012-03-06 04:44:08
【问题描述】:
假设我在 PHP 中有两个类,一个是书籍类,一个是作者类。假设我要创建一个新的书对象。
// $book is now a book class
$book = new book('War and Peace');
现在假设我想要那本书的作者。为此,我的对象设置需要我从书中获取作者类。
// gets an author class chained with a method to get it's name
$author = $book->getAuthor()->getName();
在 $book->getAuthor() 调用中,最好将作者对象“保存”到书中的属性中吗?
public function getAuthor()
{
if(is_null($this->author_object)) {
$this->author_object = new author($this->author_name);
}
return $this->author_object;
}
这个例子可能不是最好的,但我希望它很好地代表了我的问题。另外,我已经知道数据库查找对性能有很大影响,所以暂时不需要这样做。
基本上我的问题是什么更好,如果需要,再次创建作者对象,或者将作者对象保存为属性,因此不需要再次创建它。
【问题讨论】:
标签: php performance oop class object