Search code examples
phpobjectmethodsextend

Extend class methods in PHP


I am doing a custom CMS and I have built my base content class like this:

class Content
{
  public $title;
  public $description;
  public $id;

  static function save()
  {
    $q = "[INSERT THE DATA TO BASE CONTENT TABLE]";
  }
}

class Image extends Content
{
  public $location;
  public $thumbnail;

  public function save()
  {
     // I wanted to do a Content::save() here if I 
     //  declare Contents::save() as static
     $q = "[INSERT THE DATA TO THE IMAGE TABLE]";
  }
}

My problem is this I know that static function cannot use $this but I know that Content::save() needs to use it.

I want Image::save() to call Content::save() but I wanted them to be both named save() and be declared public and not static because I need $this.

Will the only solution be renaming Content::save() so I can use it within Image::save()?

Or is there a way of extending methods?


Solution

  • You can use parent to get the upper class. Even though in the following sample you call it using parent::Save, you can still use $this in the parent class.

    <?php
    
    class A
    {
        public function save()
        {
            echo "A save";
        }
    }
    
    class B extends A
    {
        public function save()
        {
            echo "B save";
            parent::save();
        }
    }
    $b = new B();
    $b->save();
    ?>