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?
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.
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.
Classes, case classes, objects, and traits can all extend no more than one class but can extend multiple traits at the same time.
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.
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();
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With