Table of Contents
Objectives of this article:
(1) Understand the definition of the Final keyword in PHP (What)
(2) Understand the role of the Final keyword in PHP (Why)
(3) Understand the usage scenarios of the Final keyword in PHP (Where)
(4) Master the specific implementation of the Final keyword in PHP (How)
with confidence (5), specific code
(6) Apply what you have learned
Summary:
Home Backend Development PHP Tutorial Detailed explanation of the Final keyword in object-oriented PHP (code example)

Detailed explanation of the Final keyword in object-oriented PHP (code example)

May 25, 2020 pm 04:31 PM
final object-oriented

Objectives of this article:

1. Understand the definition of the Final keyword in PHP

2. Understand the role of the Final keyword in PHP

3. Understand the Final keyword in PHP Keyword usage scenarios

4. Master the specific implementation of the Final keyword in PHP

Still following the previous consistent thinking, we will learn through the 3W1H method, so first let’s understand it

(1) Understand the definition of the Final keyword in PHP (What)

If you add final before a class, then this class cannot be inherited. If you add final before a method, Then this method cannot be overridden

(2) Understand the role of the Final keyword in PHP (Why)

The main functions are 2 points:

1. Prevent Classes are inherited

2. Prevent class methods from being overridden

(3) Understand the usage scenarios of the Final keyword in PHP (Where)

If you want a class If there is no subclass, or the method of a class cannot be overridden, then you can consider using final implementation

(4) Master the specific implementation of the Final keyword in PHP (How)

Summary:

1. The definition format of the final class is: final class class name {}

2. Pay special attention to the fact that only PHP5 has the concept of final keyword. This concept did not exist before PHP5

3. The definition format of the final method is: final public (or protected) function method name (parameters...){}

4. Once a class is defined as a final class, it cannot Inherited, that is, it cannot have subclasses

5. Once a method is defined as a final method, it cannot be overridden by a subclass

All the summaries are based on practice. So next, we still have to prove it one by one, so that we can use

with confidence (5), specific code

1, case one:

Practical goals:

1. The definition format of the final class is: final class class name {}

<?php
//定义“人”类
final class Human{
    public function eat(){
        echo "Human 中的eat方法被执行了<br/>";
    }
}

$human = new Human();
$human->eat();
?>
Copy after login

The operation result is:

The eat method in Human is Executed

2. Case 2:

Practical goal:

1. The definition format of the final method is: final public (or protected) function Method name (parameters...){}

<?php
class Human{
    final public function eat(){
        echo "Human 中的 类型为final的eat方法被执行了<br/>";
    }
}
$human = new Human();
$human->eat();
?>
Copy after login

The operation result is:

The final eat method in Human is executed

3. Case 3:

Practical goals:

1. Once a class is defined as a final class, it cannot be inherited, that is, it cannot have subclasses

<?php
//定义“人”类
final class Human{
    public function eat(){
        echo "Human 中的 类型为final的eat方法被执行了<br/>";
    }
}

//定义Nba球员类
class NbaPlayer extends Human{
    public function eat(){
        
    }
}
?>
Copy after login

The running result is:

Fatal error: Class NbaPlayer may not inherit from final class (Human) in D:\E-class\class-code\classing\index.php on line 14

4. Case 4:

Practical goal:

1. Once a method is defined as a final method, it cannot be overridden by a subclass

<?php
//定义“人”类
class Human{
    final public function eat(){
        echo "Human 中的 类型为final的eat方法被执行了<br/>";
    }
}

//定义Nba球员类
class NbaPlayer extends Human{
    public function eat(){
        echo "NbaPlayer中的eat方法,重写了父类的eat方法<br/>";
    }
}
?>
Copy after login

The running result is:

Fatal error: Cannot override final method Human::eat() in D:\E-class\class-code\classing\index.php on line 14

(6) Apply what you have learned

So far, we should have a clear understanding of final. Next, apply what we have learned and use the knowledge we have learned to solve the following problems Question

Question: Based on years of experience, many data operation methods can actually be reused. In addition to being used in one project, they can be used in many projects, and they can be used in many places in a project. Reuse, so I plan to encapsulate these common methods into a class, but this class does not need to have subclasses, and I don’t want the methods inside to be overridden. What should I do?

Idea analysis:

1. Create a class that contains common data operation methods

2. Because you don’t want the class to be Inheritance, so combined with the role of final, we can define the class as a final class

3. Once a class is defined as a final class, the methods inside will naturally not be overridden, because there are no subclasses. How can we rewrite it in a subclass?

The specific code is as follows:

<?php
final class MyDataOpClass{
    public function abs(){
        //求绝对值
    }
    //产生随机数
    public function rand(){
        echo "产生随机数方法";
    }
    //获取数组中的最大值
    public function getMax($numArr){
        
    }
    //获取数组中的最小值
    public function getMin($numArr){

    }
    //其他方法就此省略
}
$mymath = new MyDataOpClass();
$mymath->rand();
?>
Copy after login

The running results are as follows:

Generate random number method

Explanation: This example is a bit simple, but I hope everyone will pay attention to their own analysis of ideas and be as accurate and clear as possible

Summary:

1. The main content of this article Explained the definition and function of final as well as the specific implementation

I hope this article can bring you some help, thank you all! ! !

The above is the detailed content of Detailed explanation of the Final keyword in object-oriented PHP (code example). For more information, please follow other related articles on the PHP Chinese website!

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
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)

Hot Topics

Java Tutorial
1675
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
How to implement object-oriented event-driven programming using Go language How to implement object-oriented event-driven programming using Go language Jul 20, 2023 pm 10:36 PM

How to use Go language to implement object-oriented event-driven programming Introduction: The object-oriented programming paradigm is widely used in software development, and event-driven programming is a common programming model that realizes the program flow through the triggering and processing of events. control. This article will introduce how to implement object-oriented event-driven programming using Go language and provide code examples. 1. The concept of event-driven programming Event-driven programming is a programming model based on events and messages, which transfers the flow control of the program to the triggering and processing of events. in event driven

The difference between final, finally, and finalize in Java The difference between final, finally, and finalize in Java Feb 19, 2024 pm 12:16 PM

The difference between final, finally, and finalize in Java requires specific code examples. In Java programming, you often encounter the three keywords final, finally, and finalize. Although they are spelled similarly, they have different meanings and usages. This article will explain the differences between these three keywords in detail and give code examples to help readers better understand. 1. Final keyword The final keyword can be used for classes, methods and variables. Its function is to make the modified class

What is the importance of @JsonIdentityInfo annotation using Jackson in Java? What is the importance of @JsonIdentityInfo annotation using Jackson in Java? Sep 23, 2023 am 09:37 AM

The @JsonIdentityInfo annotation is used when an object has a parent-child relationship in the Jackson library. The @JsonIdentityInfo annotation is used to indicate object identity during serialization and deserialization. ObjectIdGenerators.PropertyGenerator is an abstract placeholder class used to represent situations where the object identifier to be used comes from a POJO property. Syntax@Target(value={ANNOTATION_TYPE,TYPE,FIELD,METHOD,PARAMETER})@Retention(value=RUNTIME)public

In Java, is it possible to define a constant using only the final keyword? In Java, is it possible to define a constant using only the final keyword? Sep 20, 2023 pm 04:17 PM

A constant variable is a variable whose value is fixed and only one copy exists in the program. Once you declare a constant variable and assign a value to it, you cannot change its value again throughout the program. Unlike other languages, Java does not directly support constants. However, you can still create a constant by declaring a variable static and final. Static - Once you declare a static variable, they will be loaded into memory at compile time, i.e. only one copy will be available. Final - Once you declare a final variable, its value cannot be modified. Therefore, you can create a constant in Java by declaring the instance variable as static and final. Example Demonstration classData{&am

PHP Advanced Features: Best Practices in Object-Oriented Programming PHP Advanced Features: Best Practices in Object-Oriented Programming Jun 05, 2024 pm 09:39 PM

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

Explore object-oriented programming in Go Explore object-oriented programming in Go Apr 04, 2024 am 10:39 AM

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

Analyzing the Flyweight Pattern in PHP Object-Oriented Programming Analyzing the Flyweight Pattern in PHP Object-Oriented Programming Aug 14, 2023 pm 05:25 PM

Analyzing the Flyweight Pattern in PHP Object-Oriented Programming In object-oriented programming, design pattern is a commonly used software design method, which can improve the readability, maintainability and scalability of the code. Flyweight pattern is one of the design patterns that reduces memory overhead by sharing objects. This article will explore how to use flyweight mode in PHP to improve program performance. What is flyweight mode? Flyweight pattern is a structural design pattern whose purpose is to share the same object between different objects.

See all articles