I'm using a tree data structure in PHP. The structure is similar to this;
- I have a 'book' object that has properties like 'title' and 'author' and a property called 'chapters'. This is an array of 'chapter' objects.
- Each 'chapter' object has a properties like 'chapter number' and a property called 'pages' - an array of page objects.
- Each page object contains a property called 'text' which is the text to display on the page, and method called as_html that generates the text as an html fragment.
To print out the book, I'd have a method in the book object called 'print' which would do something like;
foreach($this->chapters as $chapter)
foreach($chapter->pages as $page)
So, could anyone tell me whether it is possible for a method in a page object to access the properties of the book to which it belongs? I'm hoping to be able to put something in the as_html method to, for example, insert the title of the book and the author.
Any help gratefully received!
It is difficult to say without seeing your classes for Book, Chapter, and Page. It seems like you have three different classes, one for each element of your book, right?
Yes, that's right. I have classes called Book, Chapter and Page.
A Book contains an array of several Chapter objects, and each Chapter object could contain several Page objects.
My view at the moment is that the Chapter class needs a property called parent_book and when the Chapter is instantiated, this property is set to be a reference to the Book object. Likewise, a Page has a property called parent_chapter. Then I might be able to do something like this inside a particular Page object;
to get the book title. Just seems a bit messy.
doing it that way isn't that big an issue as long as you pass the objects by reference and aren't cloning them
This topic is now closed. New replies are no longer allowed.