Quick introduction to PHP object-oriented PHP tutorials

Source: Internet
Author: User
Quickly learn about PHP object-oriented. Object-oriented concepts object-oriented programming (ObjectOrientedProgramming, OOP, object-oriented programming) is a computer programming architecture. one basic principle of OOP is that computer programs are object-oriented concepts.

Object-oriented Programming (Object Oriented Programming, OOP, object-oriented Programming) is a computer Programming architecture, one basic principle of OOP is that a computer program is composed of a single unit or object that can act as a subroutine. OOP achieves three objectives of Software Engineering: reusability, flexibility, and scalability. To achieve the overall operation, each object can receive, process, and send information to other objects. Object-oriented has always been a hot topic in the field of software development. first, object-oriented is in line with the general rules of human beings. Second, the use of the object-oriented method can make all parts of the system perform their duties and do their best. Open a door for programmers to make their programming code simpler, easier to maintain, and more reusable. Some people say that PHP is not a real object-oriented language. this is a fact. PHP is a hybrid language. you can use OOP or traditional procedural programming. However, for large projects, you may need to use pure OOP in PHP to declare classes and use only objects and classes in your project. I will not talk much about this concept first, because many of my friends are far away from object-oriented programming because they cannot understand it when they come into contact with the object-oriented concept, so they don't want to learn it anymore. After reading the entire content, you can understand the concept.

What is a class, what is an object, the relationship between a class and an object?

Class Concept: A class is a set of objects with the same attributes and services. It provides a unified abstract description for all objects belonging to this class, which includes two main parts: attribute and service. In an object-oriented programming language, a class is an independent program unit. it should have a class name and contain two main parts: attribute description and service description.

Object: an object is an entity used to describe objective things in a system. it is a basic unit of a system. An object consists of a group of attributes and a group of services that operate on these attributes. From a more abstract point of view, an object is an abstraction of some things in the problem domain or implementation domain. it reflects the information that the things need to be stored in the system and its role; it is the encapsulation body of a set of attributes and a group of services that have the right to operate on these attributes. The objective world is composed of links between objects.

The relationship between a class and an object is like the relationship between a mold and a casting. The instantiation result of a class is an object, and the abstraction of a class object is a class. Class describes a group of objects with the same features (attributes) and the same behavior (methods.

The above is probably their definition. maybe you are new to object-oriented friends and should not be confused by concepts. here is an example for you, if you want to buy several assembled PCs in Zhongguancun, what do you do when you get there? are the installation engineers sitting with you, based on the information you provide, complete an installation configuration sheet with you. this configuration sheet can be considered a class, and it is a piece of paper, however, it records the information of the PC you want to buy. if you use this configuration item to buy 10 machines, the 10 machines are all composed of the configuration items, therefore, these 10 machines are of the same type or category. So what is an object? the instantiation result of the class is an object. the machine that is configured (instantiated) with this configuration sheet is an object, which is an object that we can operate on. There are 10 machines and sub-databases, 10 objects. Each sub-machine is independent and can only indicate that they are in the same category. any action on one of the sub-machines will not affect the other nine machines, but I modify the class, that is to say, if one or fewer accessories are added to the configuration list, the Nine hosts that have been installed are changed. this is the relationship between classes and objects (the instantiation result of classes is objects ).

What is object-oriented programming?

If you want to build a computer classroom, you must first have a room with N computers, N tables, N chairs, and whiteboards, projector, etc. What are these? we just talked about it. this is an object. we can see entities. we can say that the units in this computer classroom are physical objects, they make up the computer classroom together. so what is the relationship between our program and the object-oriented system? Developing a system program is similar to building a computer classroom. you Abstract each independent function module into a class to form an object, which consists of multiple objects, these objects can receive information, process data, and send information to other objects. It constitutes an object-oriented program.

How to abstract a class

As mentioned above, the unit of the object-oriented program is the object, but the object is instantiated through the class, so the first thing we need to do is how to declare the class, it is easy to create a class. you only need to master the basic program syntax and definition rules. where is the difficulty? How many classes are used in a project, how many objects are used, where classes are to be defined, what kind of classes are defined, how many objects are produced by this class instance, and how many attributes are contained in the class, how many methods are there, etc. This requires the reader to analyze and design the actual problems in actual development.

Class Definition: class name {}

Use a keyword class and a class name you want and a pair of braces. The structure of this class is defined. you only need to write code in it, but what is written in it? What can I write? How to write is a complete class? As mentioned above, the class is used to let it instance out of objects for us to use, so we need to know what kind of object you want, as we mentioned above, what is written on an installation configuration sheet is what you have installed on the machine. For example, if a person is an object, how do you recommend a person you are optimistic about to your leadership? Of course, the more detailed the better:

First, you will introduce the person's name, gender, age, height, weight, phone number, home address, and so on.

Then, you will introduce what this person can do. he can drive, speak English, and use a computer.

As long as you have a little introduction, others will have a little understanding of this person. this is our description of a person. now, let's sum up that all objects are similar to class descriptions, from the description above, we can see that a class is defined in two parts: static description and dynamic description, static descriptions are what we call attributes, such as the name, gender, age, height, weight, phone number, home address, and so on. It is also the function of the person's object on the fly. for example, when a person can drive, speak English, or use a computer, we can write dynamic functions or methods into a program, functions and methods are the same. Therefore, all classes are written in terms of attributes and methods. attributes are also called member attributes of this class, and methods are called member methods of this class.

Class {
Member attributes: name, gender, age, height, weight, phone number, home address
Member method: can drive, can speak English, can use a computer
}

The variable is declared by using the keyword "var" in the class definition, that is, the class attribute is created. Although the initial value can be given when the member attribute is declared, however, when declaring a class, it is unnecessary to give the initial value of the member attribute. for example, if the name of a person is assigned "zhang san", dozens of people will be generated using this class instance, these dozens of people are called James, so there is no need to. after the instance outputs an object, we can give the initial value of the member attribute. For example, var $ somevar;

 

The above is the declaration of a class, a class declared from the attribute and method, but the member attribute should not be given the initial value during the declaration, because our class is a descriptive information and will be used to instantiate objects. for example, if 10 objects are instantiated, the names and gender of these 10 objects are, the age is different, so it is best not to assign an initial value to the member attribute here, but to each object separately.

You can use the same method to create the desired class. as long as you can define the object as a class with the attributes and methods, you can instantiate the object.

To enhance your understanding of the class, let's create a class with a wide range of shapes. let's make a rectangle and analyze it first, what are the attributes of a rectangle? What are the functions of rectangles?

Class rectangle {// The length of the attribute rectangle of the rectangle; the width of the rectangle; // The perimeter of the rectangle using the rectangle method; the area of the rectangle ;}
 

If you use this class to create multiple rectangle objects, each rectangle object has its own length and width, you can find its own length and area.

How to instantiate an object

As we have mentioned above, the unit of the object-oriented program is the object, but the object is instantiated through the class. since our class will be declared, the next step is to instantiate the object. After the class is defined, we use the new keyword to generate an object.

 

$ P1 = new Person ();
This code is the process of generating instance objects through classes. $ p1 is the object name of our instance. Similarly, $ p2 and $ p3 are also the object names of our instances, A class can instance multiple objects, each of which is independent. the code above is equivalent to three people coming out of the instance. there is no connection between each person. it only means that they are all human beings, each person has his/her own name, gender, and age. each person has a way to speak and walk, as long as it is the member attributes and member methods embodied in the class, the instantiated object contains these attributes and methods.

Like in PHP, it is also a data type that stores different types of data, and must be loaded to the memory during running, how is the object reflected in the memory? Generally speaking, memory is divided into four segments: stack space segments, heap space segments, code segments, and initialization static segments. different declarations in the program are placed in different memory segments, stack space segments are data types that occupy the same length of storage space and small space, such as integer 1, 10,100,100 0, 10000,100 000, and so on, all are 64-bit and 4-byte. So the data length is not long, and the data type that occupies a large space is put in that memory segment? Such data is stored in the heap memory. Stack memory can be directly accessed, while Stack memory cannot be directly accessed. For our object count, it is a big data type that occupies an indefinite amount of space. Therefore, the object is placed in the heap, but the object name is placed in the stack, in this way, the object can be used through the object name.

$ P1 = new Person ();
For this code, $ p1 is the object name in the stack memory, and new Person () is the real object in the heap memory.

Each instance object in the heap is stored. for example, the instance object in the heap contains the name, gender, and age. Each attribute has an address. $ P1 = new Person (); $ p1 on the right of the equal sign is a reference variable. The first address of the object is assigned to the reference variable "$ p1" through the value assignment operator "=, therefore, $ p1 is the variable that stores the first address of an object. $ p1 is placed in the stack memory. $ p1 is equivalent to a pointer pointing to an object in the heap, therefore, we can operate on objects through the reference variable $ p1, which is also called Object reference.

How to use members in an object

The above shows that the PHP object has two types of members: Member attributes and member methods. The object can be declared. $ p1 = new Person (); how can we use the object members? To access members of an object, you must use a special operator "->" to access the object members:

Object-> attribute $ p1-> name; $ p2-> age; $ p3-> sex;

Object-> method $ p1-> say (); $ p2-> run ();

 Name = "zhang san"; $ p1-> sex = "male"; $ p1-> age = 20; // the following three rows are the attributes of the $ p1 object. echo "the name of the p1 object is :". $ p1-> name."
"; Echo" the gender of the p1 object is: ". $ p1-> sex ."
"; Echo" the age of the p1 object is: ". $ p1-> age ."
"; // The following two rows access the method $ p1-> say (); $ p1-> run () in the $ p1 object (); // the following three rows assign $ p2 object attributes $ p2-> name = "Li Si"; $ p2-> sex = "female"; $ p2-> age = 30; // the following three rows are the attributes of $ p2 object. echo "p2 object name is :". $ p2-> name."
"; Echo" p2 object gender: ". $ p2-> sex ."
"; Echo" p2 object age: ". $ p2-> age ."
"; // The following two rows access the $ p2 object method $ p2-> say (); $ p2-> run (); // the following three rows assign $ p3 object attributes $ p3-> name = ""; $ p3-> sex = "male"; $ p3-> age = 40; // the following three rows are the attributes of the $ p3 object. echo "the name of the p3 object is :". $ p3-> name."
"; Echo" the sex of the p3 object is: ". $ p3-> sex ."
"; Echo" the age of the p3 object is: ". $ p3-> age ."
"; // The following two rows access the $ p3 object's method $ p3-> say (); $ p3-> run ();?>

From the above example, we can see that only the members in the object need to access the members in the object in the form of object-> attribute, object-> method, and there is no second method to access the members in the object.

Use of Special reference "$ this"

Now we know how to access the members in an object. they are accessed through "object-> Member". This is the form of accessing the members in an object outside the object, so what if I want to allow methods in the object to access the attributes of the object, or call other methods of the object through methods in the object? Because all the members in the object must be called by objects, including calls between internal members of the object, a reference to this object is provided in PHP. $ this, each object has an object reference $ this to represent this object and complete the call of its members. this is meant to be "this". in the above instance, we instantiate three instance objects $ P1, $ P2, and $ P3, each of which has a $ this representing the objects $ p1, $ p2, and $ p3 respectively.

We can see that $ this refers to the reference of this object inside the object. it is used in the same way as the members of the calling object and the members of the calling object outside the object.

$ This-> attribute $ this-> name; $ this-> age; $ this-> sex;

$ This-> method $ this-> say (); $ this-> run ();

Modify the instance above to allow everyone to name themselves, gender and age:

 Name. "Gender:". $ this-> sex. "My age is:". $ this-> age ."
";}Function run () // The way this Person can walk {echo" this Person is walking ";}}$ p1 = new Person (); // Create an instance object $ p1 $ p2 = new Person (); // Create an instance object $ p2 $ p3 = new Person (); // Create an instance object $ p3 // the following three rows assign $ p1 object attributes $ p1-> name = "Zhangsan"; $ p1-> sex = "male "; $ p1-> age = 20; // The method for accessing the $ p1 object $ p1-> say (); // the following three rows assign $ p2 object attributes $ p2-> name = "Li Si"; $ p2-> sex = "female"; $ p2-> age = 30; // the following method of accessing the $ p2 object $ p2-> say (); // the following three rows assign $ p3 object attributes $ p3-> name = "Wang Wu "; $ p3-> sex = "male"; $ p3-> age = 40; // The following method of accessing the $ p3 object $ p3-> say ();?>

Analyze this method:
Function say () // The way this person can speak
{
Echo "My name is :". $ this-> name. "Gender :". $ this-> sex. "My age is :". $ this-> age."
";
}
The say () method is available for $ p1, $ p2, and $ p3 objects. $ this represents the three objects and calls the corresponding attributes, print the attribute value, which is the way to access the object attribute inside the object. if you call the run () method in the say () method, you can also call the run () method in the say () method () in this method, $ this-> run () is used to complete the call.

Constructor and constructor

Most classes have a special method called constructor. When an object is created, it automatically calls the constructor, that is, when the new keyword is used to instantiate the object, the constructor is automatically called.

The constructor declaration is the same as that of other operations, but 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, which can still be used in PHP5, but it is rarely used now, in this way, the constructor can be made independent of the class name. when the class name changes, you do not need to change the corresponding constructor name. For backward compatibility, if a class does not have a method named _ construct (), PHP will search for a method written in php4 with the same name as the class name.

Only one constructor can be declared in a class. Instead, the constructor is called only once every time an object is created, so it is usually used to execute some useful initialization tasks. For example, assign an initial value to a property when creating an object.

 Initial value $ this-> name = $ name; // The $ sex passed in through the constructor gives the Member attributes $ this-> sex the initial value $ this-> sex = $ sex; // assign the $ age passed in by the constructor to the member attribute $ this-> age with the initial value $ this-> age = $ age ;} // function say () {echo "My name is :". $ this-> name. "Gender :". $ this-> sex. "My age is :". $ this-> age."
";}}// Create three objects $ p1, p2, and $ p3 through the constructor, name, gender, and age $ p1 = new Person ("zhang san", "male", 20); $ p2 = new Person ("Li Si ", "Female", 30); $ p3 = new Person ("Wang Wu", "male", 40 ); // access the method of speaking in the $ p1 object below $ p1-> say (); // access the method of speaking in the $ p2 object below $ p2-> say (); // the following method is used to access the $ p3 object $ p3-> say ();?>

The constructor is opposite to the constructor. The Destructor is newly added to PHP5 and does not contain the Destructor in PHP4. The Destructor allows you to perform operations or complete some functions before destroying a class, such as closing a file and releasing a result set, the Destructor is executed when all references to an object are deleted or when the object is explicitly destroyed, that is, the destructor is called before the object is destroyed in the memory. Similar to the constructor name, the destructor name of a class must be _ destruct (). The Destructor cannot contain any parameters.

 Initial value $ this-> name = $ name; // The $ sex passed in through the constructor gives the Member attributes $ this-> sex the initial value $ this-> sex = $ sex; // assign the $ age passed in by the constructor to the member attribute $ this-> age with the initial value $ this-> age = $ age ;} // function say () {echo "My name is :". $ this-> name. "Gender :". $ this-> sex. "My age is :". $ this-> age."
";}// This is a destructor. before the object is destroyed, call function _ destruct () {echo" goodbye ". $ this-> name ."
";} // Create three objects $ p1, p2, and $ p3 through the constructor, name, gender, and age $ p1 = new Person ("zhang san", "male", 20); $ p2 = new Person ("Li Si ", "Female", 30); $ p3 = new Person ("Wang Wu", "male", 40 ); // access the method of speaking in the $ p1 object below $ p1-> say (); // access the method of speaking in the $ p2 object below $ p2-> say (); // the following method is used to access the $ p3 object $ p3-> say ();?>
Encapsulation

Encapsulation is one of the three main features of object-oriented programming. encapsulation is to combine object attributes and services into an independent unit and conceal the internal details of objects as much as possible. It has two meanings: 1. combine all attributes of an object with all services to form an inseparable independent unit (that is, an object ). 2. information hiding, that is, hiding the internal details of objects as much as possible to form a boundary (or a barrier) for external entities, and retaining only limited external interfaces to associate them with external entities.

The encapsulation principle is reflected in the software: the internal data (attributes) of the object cannot be freely accessed for parts other than the object ), this effectively avoids the "cross-infection" caused by external errors, so that software errors can be localized, greatly reducing the difficulty of error detection and troubleshooting.

Let's explain it with an example. if a person's object has attributes such as age and salary, the attributes such as personal privacy do not want others to get them at will, if you do not use encapsulation, others can get it if they want to know it, but if you encapsulate it, others will not be able to get the encapsulated attribute unless you say it yourself, otherwise, no one else can get it.

For example, a personal computer has a password, so you don't want others to log on, copy and paste it in your computer. There is also an object like a person, the attributes of height and age, which can only be increased by oneself, and cannot be randomly assigned by others.

Use the private keyword to encapsulate attributes and methods:

Original member: var $ name; // declare the name of a person var $ sex; // declare the gender var $ age; // declare the person's age function run () {.......} Change to the encapsulation form: private $ name; // use the private keyword to encapsulate the private $ sex of a person's name; // use the private keyword to encapsulate the private $ age of a person's gender; // encapsulate the age of a person using the private keyword private function run (){......} // Encapsulate a person's walking method using the private keyword. note: As long as there are other keywords before the member attribute, remove the original keyword "var ".

You can encapsulate a member (member attribute and member method) in private mode. The encapsulated members cannot be directly accessed outside the class, and can only be accessed inside the object;

Private members cannot be accessed externally, because private members can only access the object themselves. for example, the $ p1 object wants to describe its private attributes, you can access the private attribute in the method "say. (No access control is added. The default value is public and can be accessed anywhere)

Because the constructor is the default public method (the constructor should not be set to private), it can be accessed outside the class so that you can use the constructor to create an object, the constructor is also a function in the class, so you can use the constructor to assign an initial value to the private attribute. The method of "Say ()" is public by default, so you can access it outside and state its own private property.

From the above example, we can see that private members can only be used inside the class and cannot be directly accessed outside the class, but they have access permissions within the class, so sometimes we need to assign values to and read private attributes outside the class, that is, to provide some accessible interfaces to the class, the constructor in the above example is a value assignment form, however, the constructor only assigns a value when creating an object. if we want to assign a value to an existing object, if you also use the constructor to pass values, a new object is created, which is not an existing object. Therefore, we need to make some interfaces that can be accessed externally for private attributes. The purpose is to change and access the attribute values when an object exists, this can be done only for attributes that need to be changed by the outside. the attributes that do not want to be accessed by the outside do not use such interfaces, so as to achieve the purpose of encapsulation, all functions are completed by the object itself, providing as few operations as possible for the outside.

Object-oriented Programming (Object Oriented Programming, OOP, object-oriented Programming) is a computer Programming architecture. one basic principle of OOP is that computer programs are...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.