Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement inheritance in PHP

Shulou Source: shulou.com Published: 2022-06-03 20:17:42 10月16日 Update

This article is about how to implement inheritance in PHP. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

The details are as follows:

Inherit

Let's look at two categories first.

Output:

Cd1 (bobbleson, bob): playing time-50

Book1 (harrelson, harry): page count-30

Comments: these two classes, the code repeatability is too high, there are similarities and differences. It is better to use inheritance to simplify processing.

Using inheritance to deal with

Output:

Cd1 (bobbleson, bob): playing time-50

Book1 (harrelson, harry): page count-30

Comments: inheritance is a good way to solve the problems of differences and similarities.

Further optimize the processing

Output:

Cd1 (bobbleson, bob): playing time-50

Book1 (harrelson, harry): page count-30

Comments: here we put the common attributes in the parent class and other personality attributes in our own class. And set your own constructor to inherit the constructor of the parent class.

Methods that further inherit the parent class

Output:

Cd1 (bobbleson, bob): playing time-50

Book1 (harrelson, harry): page count-30

Comments: the same results can be optimized and then optimized. Here inherits the methods of the parent class. Parent::getSummaryLine (). But this one is used less.

Continue to add some interesting content

Output:

Cd1 (bobbleson, bob): playing time-50

Price: 1

Book1 (harrelson, harry): page count-30

Price: 4

Comments: discounts are added to the parent class, and the getPrice method is modified after book inheritance, so the discount is not valid for book.

Privatization property, which is set and obtained by method

Output:

Cd1 (bobbleson, bob): playing time-50

Book1 (harrelson, harry): page count-30

Thank you for reading! This is the end of the article on "how to achieve inheritance in PHP". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Tags: Methods processing output attributes content discounts two differences more articles into one good practical same interesting personality code functions articles Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL vpn OPPO Reno Docker Linux