


PHP implements parent calling the constructor method and overridden method of the parent class_PHP tutorial
php implements parent to call the constructor method of the parent class and the overridden method
This article mainly introduces the php implementation of parent to call the parent class constructor method and the overridden method. Based on the previous article about using class inheritance to solve the problem of code duplication, we further analyzed the related techniques of parent calling the parent class's construction method and being overwritten, which has certain reference value. Friends in need can refer to it
The example in this article describes how PHP implements parent to call the constructor method and overridden method of the parent class. Share it with everyone for your reference. The specific analysis is as follows:
Override: Redesigned.
When defining a constructor in a subclass, you need to pass parameters to the constructor of the parent class, otherwise we may get an incompletely constructed object.
To call the method of the parent class, you must first find a way to reference the class itself: handle. PHP provides the parent keyword for this.
parent calls the constructor of the parent class
To reference a method of a class rather than an object, use :: (two colons) instead of ->.
So, parent::__construct() means calling the __construct() method of the parent class.
Modify the code in the previous article "Using Class Inheritance to Solve Code Duplication and Other Problems" so that each class only processes its own data:
Copy the code The code is as follows:
// Starting from this article, the first letter of the class name must be capitalized, and the writing method is standardized
class ShopProduct{ // Declare class
public $title; // declare attributes
public $producerMainName;
public $producerFirstName;
public $price;
function __construct($title,$firstName,$mainName,$price){
$this -> title = $title; // Assign the passed value to the attribute title
$this -> producerFirstName= $firstName;
$this -> producerMainName = $mainName;
$this -> price= $price;
}
function getProducer(){ //Declaration method
return "{$this -> producerFirstName }"."{$this -> producerMainName}";
}
function getSummaryLine(){
$base = "{$this->title}( {$this->producerMainName},";
$base .= "{$this->producerFirstName} )";
return $base;
}
}
class CdProduct extends ShopProduct {
public $playLenth;
function __construct($title,$firstName,$mainName,$price,$playLenth){
parent::__construct($title,$firstName,$mainName,$price);
$this -> playLenth= $playLenth;
}
function getPlayLength(){
return $this -> playLength;
}
function getSummaryLine(){
$base = "{$this->title}( {$this->producerMainName},";
$base .= "{$this->producerFirstName} )";
$base .= ":playing time - {$this->playLength} )";
return $base;
}
}
// Define class
class BookProduct extends ShopProduct {
public $numPages;
function __construct($title,$firstName,$mainName,$price,$numPages){
parent::__construct($title,$firstName,$mainName,$price);
$this -> numPages= $numPages;
}
function getNumberOfPages(){
return $this -> numPages;
}
function getSummaryLine(){
$base = "{$this->title}( {$this->producerMainName},";
$base .= "{$this->producerFirstName} )";
$base .= ":page cont - {$this->numPages} )";
return $base;
}
}
?>
Each subclass calls the parent class's constructor before setting its own properties. The base class (parent class) now only knows its own data, and we should try to avoid telling the parent class any information about the subclass. This is a rule of thumb. Think about it if the information of a certain subclass should be "confidential" , as a result, the parent class knows its information, and other subclasses can inherit it, so that the subclass's information is not kept confidential.
parent calls the overridden method of the parent class
The parent keyword can be used in any method that overrides the parent class. When overriding a method of a parent class, we do not want to delete the function of the parent class, but extend it. This can be achieved by calling the method of the parent class in the current object.
Looking at the code above, you can find that a lot of code is repeated in the getSummaryLine() method in the two subclasses. We should make use of the functionality that already exists in the ShopProduct class instead of redundant development:
Copy the code The code is as follows:
function getSummaryLine(){
$base = "{$this->title}( {$this->producerMainName},";
$base .= "{$this->producerFirstName} )";
return $base;
}
// Subclass: CdProduct
function getSummaryLine(){
$base = parent::getSummaryLine();
$base .= ":playing time - {$this->playLength} )";
return $base;
}
// Subclass: BookProduct
function getSummaryLine(){
$base = parent::getSummaryLine();
$base .= ":page cont - {$this->numPages} )";
return $base;
}
We have completed the "core" function for the getSummaryLine() method in the parent class ShopProduct, and then simply call the parent class method in the subclass, and then add more data to the summary string, and the method expansion is realized.
I hope this article will be helpful to everyone’s PHP programming design.

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

Fibers was introduced in PHP8.1, improving concurrent processing capabilities. 1) Fibers is a lightweight concurrency model similar to coroutines. 2) They allow developers to manually control the execution flow of tasks and are suitable for handling I/O-intensive tasks. 3) Using Fibers can write more efficient and responsive code.

The PHP community provides rich resources and support to help developers grow. 1) Resources include official documentation, tutorials, blogs and open source projects such as Laravel and Symfony. 2) Support can be obtained through StackOverflow, Reddit and Slack channels. 3) Development trends can be learned by following RFC. 4) Integration into the community can be achieved through active participation, contribution to code and learning sharing.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.


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

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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