Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 268
Rolando Cruz Avatar asked Sep 09 '11 09:09

Rolando Cruz


People also ask

How do you extend a class method?

In Python, when a subclass defines a function that already exists in its superclass in order to add some other functionality in its own way, the function in the subclass is said to be an extended method and the mechanism is known as extending.

What is the use of extend () in PHP?

The extends keyword is used to derive a class from another class. This is called inheritance. A derived class has all of the public and protected properties of the class that it is derived from.

Can you extend 2 classes in PHP?

Classes, case classes, objects, and traits can all extend no more than one class but can extend multiple traits at the same time.

What are the __ construct () and __ destruct () methods in a PHP class?

Example# __construct() is the most common magic method in PHP, because it is used to set up a class when it is initialized. The opposite of the __construct() method is the __destruct() method. This method is called when there are no more references to an object that you created or when you force its deletion.


1 Answers

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();
?>
like image 139
TJHeuvel Avatar answered Sep 30 '22 20:09

TJHeuvel