


Construction, destruction and encapsulation in object-oriented php_PHP tutorial
The declaration of a constructor is the same as the declaration of other operations, except that its name must be __construct(). Encapsulation is to combine the properties and services of the object into an independent and identical unit, and to hide the internal details of the object as much as possible
Construction method and destructor method
Construction method:
Most classes have a special method called a constructor. When an object is created, it will automatically call the constructor, that is, when the new keyword is used to instantiate the object, the constructor will be automatically called.
The declaration of a constructor is the same as the declaration of other operations, except that its name must be __construct(). This is a change in PHP5. In previous versions, the name of the constructor must be the same as the class name. This can still be used in PHP5, but few people use it now. The advantage of this is that the constructor can be Independent of the class name, there is no need to change the corresponding constructor name when the class name changes. For backward compatibility, if there is no method named __construct() in a class, PHP will search for a constructor method written in php4 with the same name as the class name.
Format: function __construct ([parameter]) { ... ... }
Only one constructor can be declared in a class, but the constructor will only be called once every time an object is created. This method cannot be called actively, so it is usually used to perform some useful initialization tasks. For example, the corresponding properties are assigned initial values when the object is created.
The code is as follows | Copy code |
//Create a human
//The following are the member attributes of people //Define a constructor parameter as name $name, gender $sex and age $age //This person’s way of speaking //Create three objects $p1, p2, $p3 through the construction method, and pass in three different actual parameters: name, gender and age //The following accesses the speaking method in the $p1 object The output result is: |
Destructor:
The opposite of a constructor is a destructor. The destructor is a newly added content of PHP5. There is no destructor in PHP4. The destructor allows you to perform some operations or complete some functions before destroying a class, such as closing files, releasing result sets, etc. The destructor will be deleted when all references to an object are deleted or when the object is explicitly destroyed. When executed, that is, the destructor is called before the object is destroyed in memory. Similar to the name of the constructor, the name of a class's destructor must be __destruct(). The destructor cannot take any parameters.
Format: function __destruct ( ) { ... ... }
The code is as follows | Copy code | ||||
//Create a human
|
Encapsulation
Encapsulation is one of the three major characteristics of object-oriented programming. Encapsulation is to combine the properties and services of an object into an independent and identical unit, and to hide the internal details of the object as much as possible. It contains two meanings: 1. .Combines all the attributes and all services of the object to form an indivisible independent unit (i.e. object). 2. Information hiding, that is, hiding the internal details of the object as much as possible, forming a boundary (or forming a barrier) to the outside world, and retaining only a limited external interface to connect it with the outside.
The reflection of the principle of encapsulation in software is that it requires that parts other than the object cannot access the internal data (properties) of the object at will, thus effectively avoiding the "cross-infection" of external errors and enabling software errors to Localization greatly reduces the difficulty of error checking and troubleshooting.
Let’s use an example to illustrate. Suppose a person’s object has attributes such as age and salary. Such personal privacy attributes are not something that other people can obtain at will. If you don’t use encapsulation, then others can’t. You can get it if you know it, but if you encapsulate it, others will have no way to obtain the encapsulated attributes. Unless you tell it yourself, others will have no way to get it. For example, personal computers have a password, and you don't want others to log in at will and copy and paste it into your computer. Also, for objects like people, the attributes of height and age can only be increased by oneself, and cannot be assigned values arbitrarily by others, etc.
The code is as follows | Copy code | ||||
//Use the private keyword to encapsulate properties and methods: //Use the private keyword to encapsulate properties and methods: //Change to encapsulated form:
{
Function say()
Private function run()
$p1->name="Zhang San";
echo $p1->name."";
$p1->run();
Fatal error: Cannot access private property Person::$name |
The code is as follows | Copy code |
function say() //The method this person can speak, speak his own private attributes, and you can also access private methods here
class Person //Define a constructor parameter to assign values to the private attributes name $name, gender $sex and age $age //The way this person can speak, speak his own private attributes, you can also access private methods here //Create three objects $p1, p2, $p3 through the construction method, and pass in three different actual parameters: name, gender and age //The following accesses the speaking method in the $p1 object |
The output result is:
My name is: Zhang San Gender: Male My age is: 20
My name is: Li Si Gender: Female My age is: 30
My name is: Wang Wu Gender: Male My age is: 40 Because the constructor is the default public method (do not set the constructor to private), it can be accessed outside the class, so you can use the constructor Create an object, and the constructor is also a function in the class, so you can use the constructor to assign initial values to private properties. The Say() method is public by default, so it can be accessed from the outside to tell its own private properties.
From the above example, we can see that private members can only be used inside the class and cannot be directly accessed by outside the class. However, they have permission to access inside the class, so sometimes we need to Assigning and reading private properties outside the class means providing some accessible interfaces outside the class. In the above example, the constructor method is a form of assignment, but the constructor method only assigns values when the object is created. If We already have an existing object and want to assign a value to this existing object. At this time, if you also use the constructor method to pass a value, then a new object will be created, not the existing object. . Therefore, we need to make some interfaces for private attributes that can be accessed externally. The purpose is to change and access the value of the attribute when the object exists. However, it should be noted that this can only be done for attributes that need to be changed externally. Properties that do not want to be accessed by the outside do not have such an interface, so that the purpose of encapsulation can be achieved. All functions are completed by the object itself, providing as few operations as possible to the outside world.
If you provide an interface outside the class, you can provide setting methods and get methods for private properties outside the class to operate the private properties. For example:
The code is as follows
|
Copy code
|
||||
//Private attribute age |
function setAge($age)
//Private attribute age prvate $age;
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 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 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 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 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 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.

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

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.


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool