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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

C# vs. C  : History, Evolution, and Future Prospects C# vs. C : History, Evolution, and Future Prospects Apr 19, 2025 am 12:07 AM

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

See all articles