In This Following Article I Have Demonstrated How To Create Class And Its Objects.
Let's get some basic understanding of inheritance first.
In object-oriented programming, inheritance is the mechanism of basing or creating an object or class upon another object or class, to give that object or class similar implementation.
If we use base as another object then it would be called prototype-based inheritance and if we use class then it would be called class-based inheritance.
The new classes are called subclasses or child classes or child objects.
Once we know how to write class and objects we can easily derive subclasses from it. This can save lots of time in writing code again and again. For example, if we have a User class and we want to use it to create same class Student but with some more properties in addition to user class. Imagine writing down all those lines of code for each and every time you want a new Student user. That's when this inheritance concept is very helpful.
We can do that by using extends operator. When you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.
Let's take a look at the example:
//code inside PHP
$object = new Student;
$object->name = "Jon";
$object->password = "rt456ys8^&%(*&%";
$object->phone = "111 111 1111";
$object->email = "[email protected]";
$object->class = "web development";
$object->semester = "second";
$object->display();
class User {
public $name, $password;
function setup_student_profile()
{
echo "code goes here";
}
}
class Student extends User {
public $phone, $email, $class, $semester;
function display() {
echo "Student Name: " . $this->name . "<br>";
echo "Password: " . $this->password . "<br>";
echo "Phone Number: " . $this->phone . "<br>";
echo "Email Address: " . $this->email;
echo "Email Address: " . $this->email. "<br>";
echo "Class: " . $this->class. "<br>";
echo "Semester: " . $this->semester;
}
}
In the example above, the original or base class, User, has two properties. $name and $password. Also, there is a method to create student profile into database. I have not mentioned full code in the method but that's not the focus of this article.
The Student class extends those two properties of User class as it's a subclass of User class. Also, the Student class has it's own 4 properties. $phone, $email, $class, $semester. Student class has a method of displaying the properties of the current object. It uses $this variable, which refers to the current values of the objects being accesses.
The out of the code above will be:
//output
Student Name: Jon
Password: rt456ys8^&%(*&%
Phone Number: 111 111 1111
Email Address: [email protected]
Class: web development
Semester: second
So, as you can see the subclass Student has successfully derived all the properties of it's parent class, User.
basics examples Inheritance object-oriented