search
HomeBackend DevelopmentPHP TutorialLearn PHP happily in 100 days (7)] Lecture on PHP constructor: The grievances between father and son

Foreplay part:

1. One sentence summary php:

Php is used to make web applications, among which this one is very suitable for websites, the famous wordpress is Developed by php. Please do not consider using php for applications other than web.

Explanation of some keywords involved in this article:

Gaoshangda: short for high-end atmosphere and class. The Internet is too popular, and netizens are too lazy, saying that they are all unhappy. Several versions of Php: accelerate. However, this version is too object-oriented, so it is right to ignore php4.

PHP5 If you want to develop, please download version 5.3, which is the most widely used and relatively stable. Please delete 5.0~5.2 directly. Please use it with caution after 5.4. One is because it is not popular yet, and the other is because it is not compatible with versions before 5.4 (many open source libraries on the Internet are not compatible with versions after 5.4)

PHP6 Can you download it from me? I admire you.

About learning PHP:

If you just want to quickly learn PHP syntax, please use the PHP compiler and installer under Windows. One-click installation and configuration are simple. It is not recommended to start learning PHP directly on Linux. I will wait for you to configure it. After correcting it, you are no longer interested in php.

If you have learned how to install it in a commercial environment, you must learn how to configure and develop PHP under Linux. After all, many excellent third-party supports are native to Linux, and Linux is also the best in terms of efficiency and stability. Of course, PHP's support in IIS7 is said to be good, but please don't take it too seriously, it's boring.

2. Text part:

What is a constructor

The characteristics of constructors in each language (such as java, c#, php) are somewhat different. A function that can be automatically executed when each object is initialized. This function does not need to set anything, but if you set it, it will be executed automatically. More importantly, you cannot manually call this function externally.

Generally speaking, the constructor name and class name in most languages ​​​​are the same. PHP is an exception here. It used to be like this, but in php5, although it can still be the same, it is no longer recommended that you use and classes. The function names have the same name.

Why do we need a constructor

If it is an independent single class. In fact, the constructor also plays a "convenient" role.

For example:

class A

{

function A()

{

// Do it here Some initialization work

}

}

Does this make sense? In fact, it makes no sense. You can call the things in A() externally.

So when and where does the constructor make sense? In fact, it is about objects and object inheritance. Let me give you a story-like example: There is no similar product in China for this class library. In order to prevent others from understanding it, I made the structure of the class library extremely complicated. Then accidentally sold it to multiple programmers. but? I really want to do some statistics, that is, I want to know who has used my class library so that I can feel good about myself, so I designed my base class library like this:

class Niu Niu //This It’s the name of a high-level library

{

                                                                                        Niuniu()

                                                                     to my In the mailbox, it's very unethical, isn't it?

}

//The following are other high-level functions and methods that can be called externally, briefly

}

Here we assume: If programmers want to use my functions, You must inherit my class library, otherwise you won’t understand how to call it at all:

Class 牛牛 extends 牛牛 //Note that this is directly the inheritance writing method of php

{

//It’s up to you Do it. Anyway, I will collect the information before you do it, because I have already set the constructor of the parent class.

}

So everyone knows:

1. The constructor is not created for convenience

2. It is more used for object-oriented structural design

3. Its inheritance, controllability, and systematization are the main uses of the constructor, and productization and commercialization are the main purposes of using it

4. If everyone knows how to develop IOS, everyone will see you. If the view you write inherits UITableView, then your interface will automatically render the table in the end. Do you want to know how Apple implements UITableView? There is no way to do it. The only way is to inherit it honestly and write code based on mine.

5. Programming does not mean that a program is good if it is elegant, beautiful, artistic, or difficult to understand. The master has his own purpose when writing any program. Similarly, every word a smart boss says to you has a purpose, not to reflect how good his eloquence is

Characteristics of PHP's constructor

See the above restrictions It seems to be no problem, but it can still be broken. That is, after a subclass inherits a parent class in PHP, if the subclass sets its own constructor, the parent class's function will not be executed automatically. Look at the code:

class Mavericks extends Niu Niu //Note that this is directly the inheritance writing method of PHP

{

Function Mavericks()

{

                                        // I have With my own constructor, the parent class will have less to worry about

}

}

If I write it this way, I won’t be able to perform the dirty act of "collecting information" in the constructor of the parent class.

Constructor features in PHP5

The constructor in most languages ​​​​must be the same as the class name. In fact, the above writing method is the writing method of PHP4. In PHP5, the founder used the __construct function instead. Of course, the original way of writing is still compatible

Let’s take a look at such an ultimate way of writing (Why is it called ultimate? Because I am too tired to write this, I have to stop writing)

CLASS FATHER

{

Function __ConStruct () // Here you either write it as a function father ()                   echo "father";

{

echo "son" ; //If the child has its own constructor here, "father" will not be output

" // parent::__construct(); // If you insist on executing the father's constructor, do this, don't There is no other way

}

}

$child=new child();

I will summarize the above constructor:

1. Father and son All Born from one ancestor, one family, one generation.

2. If the son has not started a family (he has no constructor), then the son must tell everyone that he is the son of XX, otherwise no one will know the son (the father's constructor will be forced to execute automatically)

3 , If the son grows up, he doesn’t want his father to be in charge. Then he must start his own family and start a business (define his own constructor). You can now tell the outside world who you are without telling others who your father is (you only execute your own constructor)

4. After my son started his career, he found that it was not possible, and sometimes he had to rely on his father to bring in contacts to help him with projects. Do it. So I can only continue to mention his father’s name outside (execute parent::__construct() to execute the constructor of the parent class)

Let’s look at the last piece of code in this chapter:

class father

{

function __construct() //Here you can either write function father() or use __construct

{

echo "Father";

                 $this ->talk();

}

}

class child extends father

{

} function child()

 {

子 Echo "Son"; // If Child has its own constructor, it will not output "father"

Parent :: __ Construct (); // There is no other way to do this

}

function talk()

{

echo "Please help my son";

}

}

$child=new child();

Look at the parent class first. You will find that initializing the parent class alone will make an error because there is no talk function in the parent class. So you can only initialize the subclass (child). If parent::__construct(); is executed, you will find that talk in the subclass is executed, but it is actually automatically executed by the constructor of the parent class.

Everyone who sees this will definitely have a new view and understanding of the PHP constructor. In fact, this is really useful. I will continue the above rhythm and use the above tone to explain this code:

1. One day, my father finally became old and could no longer go out to help his son with projects, so he could only stay at home and cook. (Initializing the parent class alone will cause an error)

2. The son went on a rampage relying on the resources brought to him by his father, and rarely went back to visit his father. He also said that his father was really useless and almost wanted to never go back again. Visiting Father

3. Finally one day, the son had a big problem in his career, and only his father’s friends could solve this problem.

4. However, the old father was sick and lay in bed all day. For the sake of his son, the father wrote a letter to his friend regardless of the past grudges, and told his son that he must give it to his friend in person before he can open it

5 , The son handed the letter to his father's friend (the constructor of the subclass enforces the constructor of the parent class)

6. The father's friend opened the letter, and the son's eyes were blurry, and the letter read: Please help My son (the constructor of the parent class automatically executes the methods of the subclass)

Okay, that’s almost all about the PHP constructor. In fact, it’s not just PHP, any development language still in use has its uniqueness. No language has a future and no language has a future. It's just that the fields are different, the customer requirements are different, and the money is different.

Here is another suggestion for you: writing programs is the same as being a human being. People who are good at being, sensible, and caring must be very popular with everyone; similarly, programmers who can consider users will definitely write code that will Be liked by users, leaders, and colleagues.

Quote from the movie "God of Cookery" Stephen Chow: What is "the best food can be made with heart"? This heart is not in a specific dish, this heart is here, in life, just like In your understanding and perception of the world.

The above introduces the content of Happy Learning PHP in 100 Days (Part 7)] Lecture on PHP Constructor: The Grievances between Father and Son, including all aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 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.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 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.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 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 Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

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

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment