Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Mar 2010
    Posts
    199
    Thanks
    78
    Thanked 5 Times in 5 Posts

    PHP OOP - Class extends

    Hi everybody.

    I'm a bit confused about php classes and how extends work.
    Say for example I want to make a blog.
    So I have a class named blog with the following methods:

    Code:
    blog_insert
    blog_update
    blog_delete
    blog_get_posts
    blog_view_post
    properties:
    Code:
    var $blog_id;
    Now this class should handle the basics I want to do with my blog post etc.
    I would then make a new instance of this class to display the blog to the page.

    But now I want for example comments in this blog.
    So I create a comment class, should this class extend the blog class ore not?
    Because I think some properties of blog could come in handy in the comment class.

    Code:
    comment_display
    comment_insert
    comment_update
    comment_delete
    If this is all wrong please explain.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Comment should not extend blog as there is no direct relation between the comment and the blog. The comment belongs to the blog, and presumably many comment will belong to blog. So the blog then requires a way of handling comments.
    For this, I'd write a blog, and a comment class with no relationship between them. I would then extend blog to a new class which I'll call commentableblog and add methods for comment handling. For ease, I would also add IteratorAggregate to it.
    PHP Code:
    class CommentableBlog extends Blog implements IteratorAggregate
    {
        private 
    $comments = array();

        public function 
    addComment(IComment $c)
        {
            
    $hash spl_object_hash($c);
            if (!isset(
    $this->comments[$hash]))
            {
                
    $this->comments[$hash] = $c;
            }
        }

        public function 
    removeComment(IComment $c)
        {
            unset(
    $this->comments[$hash]);
        }

        public function 
    getIterator()
        {
            return 
    $this->comments;
        }

    If there are methods in blog that would be handy in the comments, then you may add them during instantiation of the comment, or even better, add and remove them using a setting with the above during the add / remove comment methods.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • Users who have thanked Fou-Lu for this post:

    conware (07-15-2013)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •