Objectives of this article:
1. Understand the definition of inheritance
2. Master the benefits of inheritance
(1).Definition
Let’s look at the picture above carefully, and then do one thing to find out what they have in common
Common ground:
1. They all have some of the same attributes and methods
2. They are all human beings
Follow the definition of normal classes. If we want to implement the above two classes, we have to define them separately. All attributes and methods of the NBA player class, and then when defining the female anchor class, you have to write repeated attributes such as name, height, weight and eating methods. If there is another class called student, it means that these common The attributes and common methods have to be written again, and so on. The code will be similar in many places, which increases the redundancy of the code. Therefore, in order to solve this redundancy, in order to make the code more concise and reusable High, we can write these common attributes and methods together, and then let each class call this common attribute and method. Will it be more convenient to maintain and the code will be more concise? Then We call this approach inheritance
How to do it specifically, as shown below
We first create a "person" class, let this person Both have attributes and methods common to both classes, and then let both NBA players and female anchors inherit the "person" class
Concept: The inherited class is called the parent class, such as people, and the inherited class is called the subclass
Summary: What is inheritance? Inheritance is a method to improve the reusability of code and reduce the number of The redundancy of code is just like heredity in real life. Children will inherit part of their parents’ genes, so when you are born, you will have the common attributes and behaviors of humans
(2) Benefits of inheritance
1. Improve code reusability and save programming time and cost
The attributes and methods defined in the parent class do not require subclasses If the definition is repeated in a class, as long as the subclass inherits the parent class, it will have all the properties and methods in the parent class
2. All subclasses under the same parent class can be treated equally when calling them
For example, whether it is an NBA player or a female anchor, because they are all human beings, when we call them, we can directly call the method of the parent class, such as eating, regardless of whether the class is an NBA player or a female anchor
3. Subclasses can modify and adjust the class members defined by the parent class
a. We call it Overwrite
b. Once the subclass is modified, Execute according to the method defined by the subclass
This is equivalent to mutation
To learn anything, we must not only know the theory, but also have relevant theoretical practices. In fact, all theories are derived from practice. Yes, so sometimes I have repeatedly emphasized that although the theory is very abstract, everyone must also summarize it after they have certain practical experience, and summarize some concise and easy-to-understand "theory". After this habit is cultivated, I believe Everyone can understand a lot of knowledge more thoroughly, and at the same time, it is easier to grasp the essence of things, so that the ability to analyze problems will also be improved.
Okay, since we need to combine theory and practice, then next, we will conduct a practical demonstration through the code to see how inheritance is implemented in the code
( 3) Specific code
<?php /*** * 案例目标 * 1.掌握继承的定义 2.掌握继承的好处 */ //定义一个“人”类 class Human{ public $name = "";//姓名 public $height = "";//身高 public $weight = "";//体重 public function eat($food){ echo $this->name."在吃".$food."<br/>"; } } //女主播 class Anchors extends Human{ public $name = ""; public $stageName = ""; public function __construct( $name,$stageName ){ $this->name = $name; $this->stageName = $stageName; } public function singing(){ echo "我是女主播,我会唱歌<br/>"; } //重写方法eat public function eat($food){ echo "我是女主播,我是边唱歌边吃{$food}<br/>"; } } //Nba球员类 class NbaPlayer extends Human{ //因为父类已经有了,所以就不需要再写了,通过extends来实现 // public $name = "";//姓名 // public $height = "";//身高 // public $weight = "";//体重 public $team = "";//团队 public $playerName = "";//球员号码 public function __construct( $name,$height,$weight,$team,$playerName ){ $this->name = $name; $this->height=$height; $this->weight = $weight; $this->team = $team; $this->playName = $playerName; echo "构造函数执行了,当前对象是{$this->name}<br/>"; } //跑步 public function run(){ echo "跑步中<br/>"; } //跳跃 public function jump(){ echo "跳跃<br/>"; } //运球 public function dribble(){ echo "运球<br/>"; } //传球 public function pass(){ echo "传球<br/>"; } //投篮 public function shoot(){ echo "投篮<br/>"; } //扣篮 public function dunk(){ echo "扣篮<br/>"; } //重写方法eat ,只要名称和父类一样就是代表重写了不一定参数也要保持一样 public function eat($food){ echo "我是Nba球员,我是站着吃饭,边吃{$food}边看球赛<br/>"; } } //测试,NBA球员,没有直接定义name,身高,体重,现在输出一下看结果有没有 //创建乔丹对象 $jordon = new NbaPlayer("乔丹","1.98米","98公斤","公牛","23"); //输出乔丹对象 echo "名称= ".$jordon->name."<br/>"; //测试,NBA球员,没有直接定义eat方法,现在输出一下看结果有没有 echo $jordon->eat("苹果"); //证明第二个好处,只要是个人就可以调用它的eat方法 $linda = new Anchors("琳达","LD"); echo $linda->eat("苹果"); //测试第三个好处是否真实 //思路1.为女主播和NBA球员2个类分别重写eat方法 // 2.再次执行2个对象的eat方法 // 会发现一旦子类重写了父类的方法,那么就会调用子类自己的方法了,这里就大家自己写下,因为上面我已经调用了eat方法,一旦重写了,上面的结果会变 ?>
Through the demonstration of the above code, we summarize:
1. extends means inheritance. Through this keyword, the subclass can inherit the parent Class, sharing all attributes and methods of the parent class
2. Other features of inherited code:
● In the subclass constructor, it can also be accessed directly through $this->
● In PHP, only one class can be inherited after extends, and cannot be used to inherit multiple classes, otherwise an error will be reported
Summary:
This article In fact, there are only two goals. Knowing the definition and benefits of inheritance. Finally, we believe that we have a deeper understanding of the benefits of inheritance through code
The above is the detailed content of Object-oriented inheritance in PHP. For more information, please follow other related articles on the PHP Chinese website!

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.