简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM