Home Backend Development PHP Tutorial PHP basics How to use inheritance_PHP tutorial

PHP basics How to use inheritance_PHP tutorial

Jul 20, 2016 am 10:57 AM
c++ java p php Instructions about exist Base object belong mechanism of inherit For

Inheritance is one of the three major object-oriented mechanisms. It exists in C++, JAVA, PHP. The following is an introduction to how to use it in PHP.

Usually you need classes that have the same variables and functions as other existing classes. In fact, it would be a good exercise to define a common class that is used in all projects, and to continuously enrich this class to adapt to each specific project. To make this easier, classes can extend from other classes. An extended or derived class owns all the variables and functions of its base class (this is called "inheritance", except no one dies), and includes all the parts defined in the derived class.

The elements in the class cannot be reduced, that is, any existing functions or variables cannot be unregistered. An extension class always depends on a single base class, that is, multiple inheritance is not supported. Use the keyword "extends" to extend a class.

<ol class="dp-c">
<li class="alt"><span><span><?php  </span></span></li><li><span class="keyword">class</span><span> test {  </span></li><li class="alt"><span class="keyword">public</span><span> </span><span class="keyword">function</span><span> __construct() {   </span></li><li><span>}  </span></li><li class="alt"><span class="keyword">public</span><span> </span><span class="keyword">function</span><span> name() {   </span></li><li><span class="vars">$this</span><span>->xname(</span><span class="string">'John'</span><span>);   </span></span></li>
<li class="alt"><span>}  </span></li>
<li>
<span class="keyword">private</span><span> </span><span class="keyword">function</span><span> showName(</span><span class="vars">$name</span><span>) {   </span>
</li>
<li class="alt">
<span class="func">echo</span><span> </span><span class="string">'my name in test is '</span><span>.</span><span class="vars">$name</span><span>;   </span>
</li>
<li><span>}   </span></li>
<li class="alt"><span>}  </span></li>
<li>
<span class="keyword">class</span><span> extendTest </span><span class="keyword">extends</span><span> test {  </span>
</li>
<li class="alt">
<span class="keyword">public</span><span> </span><span class="keyword">function</span><span> __construct() {   </span>
</li>
<li><span>parent::__construct();   </span></li>
<li class="alt"><span>}  </span></li>
<li>
<span class="keyword">private</span><span> </span><span class="keyword">function</span><span> showName(</span><span class="vars">$name</span><span>) {   </span>
</li>
<li class="alt">
<span class="func">echo</span><span> </span><span class="string">'my name in extendTest is '</span><span>.</span><span class="vars">$name</span><span>;   </span>
</li>
<li><span>}   </span></li>
<li class="alt"><span>}  </span></li>
<li>
<span class="vars">$test</span><span> = </span><span class="keyword">new</span><span> extendTest();   </span>
</li>
<li class="alt">
<span class="vars">$test</span><span>->name();   </span>
</li>
<li><span>?> </span></li>
</ol>
Copy after login

The above example defines a class named Named_Cart, which has all the variables and functions of the Cart class, plus the additional variable $owner and an additional function set_owner() . Now, a named shopping cart is created in the normal way, and the owner of the shopping cart can be set and retrieved. The normal shopping cart class functions can still be used in the named shopping cart class:

<ol class="dp-c">
<li class="alt"><span><span><?php  </span></span></li><li><span class="vars">$ncart</span><span> = </span><span class="keyword">new</span><span> Named_Cart; </span><span class="comment">// 新建一个有名字的购物车 </span><span> </span></li><li class="alt"><span class="vars">$ncart</span><span>->set_owner(</span><span class="string">"kris"</span><span>); </span><span class="comment">// 给该购物车命名 </span><span> </span></span></li>
<li>
<span>print </span><span class="vars">$ncart</span><span>->owner; </span><span class="comment">// 输出该购物车主人的名字 </span><span> </span>
</li>
<li class="alt">
<span class="vars">$ncart</span><span>->add_item(</span><span class="string">"10"</span><span>, 1); </span><span class="comment">// (从购物车类中继承来的功能) </span><span> </span>
</li>
<li><span>?>  </span></li>
</ol>
Copy after login

This can also be called the "father-child" relationship. Create a class, the parent class, and use extends to create a new class based on the parent class: the child class. You can even use this new subclass to create another class based on this subclass.

Note:

A class can only be used after it is defined! If you need class Named_Cart to inherit class Cart, you must first define the Cart class. If you need to create another Yellow_named_cart class based on the Named_Cart class, you must first define the Named_Cart class. To put it simply: the order of class definitions is very important.

<ol class="dp-c">
<li class="alt"><span><span class="keyword">class</span><span> Person{  </span></span></li>
<li>
<span class="keyword">protected</span><span> </span><span class="vars">$name</span><span>;</span><span class="comment">//protected保护的权限,在子类可以访问,外部不能访问 </span><span> </span>
</li>
<li class="alt">
<span class="keyword">protected</span><span> </span><span class="vars">$age</span><span>;  </span>
</li>
<li>
<span class="keyword">protected</span><span> </span><span class="vars">$sex</span><span>;  </span>
</li>
<li class="alt">
<span class="keyword">function</span><span> __construct(</span><span class="vars">$name</span><span>,</span><span class="vars">$age</span><span>,</span><span class="vars">$sex</span><span>){  </span>
</li>
<li>
<span class="vars">$this</span><span>->name=</span><span class="vars">$name</span><span>;</span><span class="comment">//当使用this时,就算name没有声明,也会再次声明一个 </span><span> </span>
</li>
<li class="alt">
<span class="vars">$this</span><span>->age=</span><span class="vars">$age</span><span>;  </span>
</li>
<li>
<span class="vars">$this</span><span>->sex=</span><span class="vars">$sex</span><span>;  </span>
</li>
<li class="alt">
<span class="func">echo</span><span> </span><span class="string">"###############"</span><span>;  </span>
</li>
<li><span>}  </span></li>
<li class="alt">
<span class="keyword">public</span><span> </span><span class="keyword">function</span><span> say(){  </span>
</li>
<li>
<span class="func">echo</span><span> </span><span class="string">"我的名字:{$this->name},我的年龄{$this->age}:,我的性别:{$this->sex}<br/>"</span><span>;  </span>
</li>
<li class="alt"><span>}  </span></li>
<li>
<span class="keyword">protected</span><span> </span><span class="keyword">function</span><span> eat(){  </span>
</li>
<li class="alt">
<span class="func">echo</span><span> </span><span class="string">"wwwwwwwwwwwwwwwwwwwww<br>"</span><span>;  </span>
</li>
<li><span>}  </span></li>
<li class="alt">
<span class="keyword">function</span><span> run(){  </span>
</li>
<li><span>}  </span></li>
<li class="alt">
<span class="keyword">protected</span><span> </span><span class="vars">$name</span><span>;</span><span class="comment">//protected保护的权限,在子类可以访问,外部不能访问 </span><span> </span>
</li>
<li>
<span class="keyword">protected</span><span> </span><span class="vars">$age</span><span>;  </span>
</li>
<li class="alt">
<span class="keyword">protected</span><span> </span><span class="vars">$sex</span><span>;  </span>
</li>
<li><span>}  </span></li>
<li class="alt">
<span class="comment">//继承 </span><span> </span>
</li>
<li>
<span class="keyword">class</span><span> Student </span><span class="keyword">extends</span><span> Person{  </span>
</li>
<li class="alt">
<span class="keyword">var</span><span> </span><span class="vars">$school</span><span>;  </span>
</li>
<li>
<span class="keyword">function</span><span> __construct(</span><span class="vars">$name</span><span>,</span><span class="vars">$age</span><span>,</span><span class="vars">$sex</span><span>,</span><span class="vars">$school</span><span>){  </span>
</li>
<li class="alt">
<span>parent::__construct();</span><span class="comment">//调用父类的构造方法 </span><span> </span>
</li>
<li>
<span class="vars">$this</span><span>->school=</span><span class="vars">$school</span><span>;  </span>
</li>
<li class="alt"><span>}  </span></li>
<li>
<span class="comment">//重载say()方法,进行扩展 </span><span> </span>
</li>
<li class="alt">
<span class="keyword">protected</span><span> </span><span class="keyword">function</span><span> say(){</span><span class="comment">//父类使用public,子类的权限不能低于父类,可以喝父类的权限相同 </span><span> </span>
</li>
<li>
<span class="comment">//Person::say();//调用父类的say()方法 </span><span> </span>
</li>
<li class="alt">
<span>parent::say();</span><span class="comment">//调用父类say()方法,parent代表父类名,当父类名变化时也能够调用。 </span><span> </span>
</li>
<li>
<span class="func">echo</span><span> </span><span class="string">"我所在的学校{$this->school}<br/>"</span><span>;</span><span class="comment">//www.3ppt.com </span><span> </span>
</li>
<li class="alt"><span>}  </span></li>
<li>
<span class="keyword">function</span><span> study(){  </span>
</li>
<li class="alt">
<span class="func">echo</span><span> </span><span class="string">"{$this->name}在学习<br/>"</span><span>;  </span>
</li>
<li><span>}  </span></li>
<li class="alt"><span>}  </span></li>
<li>
<span class="vars">$s</span><span>=</span><span class="keyword">new</span><span> Student(</span><span class="string">"zhangsan"</span><span>,23,</span><span class="string">"男"</span><span>);  </span>
</li>
<li class="alt">
<span class="vars">$s</span><span>->say();  </span>
</li>
<li>
<span class="vars">$s</span><span>->study(); </span>
</li>
</ol>
Copy after login

Advantages of inheritance:

1. One of the three major characteristics of object-oriented

2. Openness and scalability

3. Increase code reusability

4. Improve software maintainability

5. Inheritance is useful The subclass "extends" the parent class

C++ belongs to multiple inheritance, the same class can have multiple parent classes

PHP and JAVA belong to single inheritance, the same class can only have one parent class

Whether it is multiple inheritance or single inheritance, you can have multiple subclasses

As long as you have members that can be shared when designing two classes, you can separate the shared content into one The base class uses

1. Application of class inheritance

1. Declare a subclass and use the extends keyword to inherit (extend) a parent class

2. Subclasses can inherit all content from the parent class, including member attribute methods, construction methods..., which can be used in subclasses

2. Access types Control

Although subclasses can inherit everything from the parent class, private members can only be used in this class, and cannot be used in subclasses when

is encapsulated , you can not only make the inside of your own class accessible, but also make the subclasses usable, but the outside of the class cannot be used, as long as the permission is set to protected

3. Subclasses Overloading methods of the parent class

1. The subclass can declare the same method name as the parent class, that is, the subclass overrides the method of the parent class with the same name

2. The subclass method extends the parent class method

3. Call the overridden method in the parent class in the subclass

Use the parent class name::method name() parent ::Method name ()

4. Write the constructor in the subclass. If there is a constructor in the parent class, be sure to call the overridden constructor in the parent class

Note : Overloaded methods in subclasses cannot have lower access permissions than those in the parent class (subclasses can enlarge permissions, but cannot reduce permissions)

Hope this is helpful to you.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445786.htmlTechArticleInheritance is one of the three major object-oriented mechanisms. It exists in C++, JAVA, and PHP. The following is an introduction to how to use it in PHP. Usually you need some classes, these classes...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Java Made Simple: A Beginner's Guide to Programming Power Java Made Simple: A Beginner's Guide to Programming Power Oct 11, 2024 pm 06:30 PM

Java Made Simple: A Beginner's Guide to Programming Power Introduction Java is a powerful programming language used in everything from mobile applications to enterprise-level systems. For beginners, Java's syntax is simple and easy to understand, making it an ideal choice for learning programming. Basic Syntax Java uses a class-based object-oriented programming paradigm. Classes are templates that organize related data and behavior together. Here is a simple Java class example: publicclassPerson{privateStringname;privateintage;

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

See all articles