Quick understanding of PHP's object-oriented _php tutorials

Source: Internet
Author: User

Object-oriented concepts

OO programming (Object Oriented programming, OOP, object-oriented programming) is a computer programming architecture, and one of the basic principles of OOP is that a computer program is composed of a single unit or object that can act as a subroutine, OOP achieves the three goals of software engineering: reusability, flexibility, and extensibility. To achieve the overall operation, each object can receive information, process data, and send information to other objects. Object-oriented has always been a hot topic in the field of software development, first of all, object-oriented conforms to the general law of human beings ' view of things. Secondly, the use of object-oriented method can make all parts of the system perform their duties and his ability. Opens the door for programmers to make their programming code simpler, easier to maintain, and more reusable. Some people say that PHP is not a true object-oriented language, which is true. PHP is a mixed language, you can use OOP, or you can use traditional procedural programming. However, for large projects, you might want to use pure OOP in PHP to declare classes, and use only objects and classes in your project. I'm not going to say much about this concept, because there are a lot of friends away from object-oriented programming is the main reason is a contact with the object-oriented concept when the understanding is not up, so do not want to learn. After reading the whole content of the reader, then go to the concept to understand it.

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

Class Concept: A class is a collection of objects that have the same properties and services. It provides a unified, abstract description of all objects that belong to the class, including two main parts of properties and services. In an object-oriented programming language, a class is a stand-alone program unit that should have a class name and consist of two main parts: a property description and a service description.

Object concept: An object is an entity used to describe an objective thing in a system, which is a basic unit of a system. An object consists of a set of properties and a set of services that operate on that set of properties. From a more abstract point of view, an object is an abstraction of a problem domain or something in the implementation domain that reflects the information and the role that the thing needs to be saved in the system; it is a set of attributes and a wrapper for a set of services that have permission to manipulate these properties. The objective world is made up of the connections between objects and objects.

The relationship between a class and an object is like the relationship between a mold and a casting, and the instantiation of a class is the object, and the abstraction of a class object is the classes. Class describes a set of objects that have the same attributes (attributes) and the same behavior (methods).

Above is probably their definition, perhaps you are just contact object-oriented friends, not to be confused by the concept of things, give you an example, if you go to Zhongguancun to buy a few assembled PC, to where you first step to do, is not installed engineers and you sit together, According to the information you provide with you to complete an installed configuration single Ah, this configuration can be imagined as a class, it is a piece of paper, but it is recorded on the PC you want to buy information, if you buy 10 machines with this configuration, then these 10 machines, are based on this configuration single, So the 10 machine is a type, it can be said to be a kind of. So what is the object, the instantiation of the class result is the object, with this configuration single configuration (instantiation) of the machine is the object, we can operate the entity, 10 machines, 10 objects. Each machine is independent, can only show that they are the same class, to one of the machines do any action will not affect the other 9 machines, but I modify the class, that is, in this configuration list with one or fewer accessories, then the installed 9 machine has changed, this is the relationship between classes and objects (class instantiation result is the object).

What is object-oriented programming

Do not say his concept, if you want to build a computer classroom, first to have a room, the room to have n computers, there are n tables, n chairs, white boards, projectors and so on, these are what, just now we said, this is the object, can see the entity, Can say this computer classroom unit is this one entity object, they together compose this computer classroom, then we are the procedure, this and object-oriented have what relation? Develop a system program and build a computer classroom. Similarly, you abstract each individual function module into a class, forming an object, composed of multiple objects that can receive information, process data, and send information to other objects, among other interactions. constitutes an object-oriented program.

How to abstract a class

As described above, the object-oriented program is the object, but the object is also through the instantiation of the class, so the first thing we have to do is how to declare the class, to make a class is very easy, as long as the basic rules of the program syntax can be done, then the difficulty is there? How many classes to use for a project, how many objects to use, where to define the class, what class to define, how many objects the class instantiates, how many properties there are in the class, how many methods are there, and so on, which requires the reader to design and summarize the actual problem analysis in the actual development.

Class definition: class Name {}

Use a keyword class and followed by a class name you want and a pair of curly braces, so that the structure of a class is defined, as long as you write code inside it, but what does it say? What can I write? How to write is a complete class? Above, the use of the class is to let it instance out of the object for us to use, it is necessary to know what you want to be the object, like the above we talk about a single installed on the list of what to write, you put out what the machine. For example, a person is an object, how do you recommend a person you are optimistic to your leadership? Of course the more detailed the better:

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

Then, you want to introduce what this person can do, can drive, speak English, can use computers and so on.

As long as you introduce a little more, others to this person a little more understanding, this is our description of a person, and now we summarize, all objects we use class to describe are similar, from the description of the above can be seen, to make a class, from the definition of the angle of two parts, the first is static description, The second is the dynamic description, the static description is what we call the property, as we see above, the person's name, gender, age, height, weight, telephone, home address and so on. Dynamic is the function of this object, such as this person can drive, can speak English, can use computer and so on, abstract into a program, we put the dynamic writing function or method, function and method is the same. Therefore, all classes are written in terms of properties and methods, and properties are called member properties of the class, and the method is called the member method of the class.

Class Person {
Member properties: Name, gender, age, height, weight, phone, home address
Member method: Can drive, speak English, can use the computer
}

Declaring a variable by using the keyword "var" in the class definition creates the property of the class, although it is possible to give the initial value when declaring the member property, but it is not necessary to assign the value to the member property at the time of declaring the class, for example, if the name of the person is "Zhang San", then use this class instance to dozens of people These dozens of people are called Zhang San, so it is not necessary that we give the member property initial value after the instance is out of the object. such as: Var $somevar;

 
  

The above is a class declaration, a class declared from the properties and methods, but the member property is best not to give the initial value at the time of declaration, because we do the person this class is a descriptive information, in the future use it to instantiate objects, such as the instantiation of 10 objects, then the 10 people, each person's name, gender, Age is different, so it's best not to assign an initial value to a member attribute in this place, but to assign values to each object individually.

The same way you can make the class you want, as long as you can use attributes and methods to describe the entity can be defined as a class, to instantiate the object.

In order to strengthen your understanding of the class, we do a class, to do a shape of the class, the shape of a wide range of points, we do a rectangular bar, first analysis, think of two aspects of analysis, the properties of the rectangle what? What are the functions of a rectangle?

Class Rectangle {//rectangle the length of the rectangle, the width of the rectangle, the circumference of the rectangle's method rectangle, the  area of the rectangle;}
 
  

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

How to instantiate an object

As we said above, object-oriented programs are objects, but objects are instantiated through classes, and since our class declares, the next step is to instantiate the object. When a class is defined, we use the New keyword to generate an object.

 
  

$p 1=new person ();
This code is the process of generating an instance object through a class, $p 1 is the name of the object we are using as an example, the same, $p 2, $p 3 is also the object name of our example, a class can instantiate multiple objects, each object is independent, the above code is equivalent to the instance of 3 people, There is no connection between each person, can only show that they are human, everyone has their own name, gender and age attributes, everyone has a way to talk and walk, as long as the class is reflected in the member properties and member methods, the instantiated object contains these properties and methods.

Like in PHP and integer, floating point type, is also a kind of data class, are stored in different types of data, in the run time to load into memory to use, then the object in memory is how to reflect it? Memory from the ROM is broadly divided into 4 paragraphs, stack space, heap space, code snippets, initialization of static segments, the program inside the different statements placed in different memory segments, stack space is the same space to occupy the same length and occupy a small space of data types, such as Integer 1, 10, 100, 1000, 10000, 100000, etc., in the memory space is equal to the length, are 64 bits 4 bytes. So the data length is variable, and the data type with large space is placed in that segment of memory? This data is placed in the heap memory. Stack memory is directly accessible, and heap memory is memory that cannot be accessed directly. The number of our objects is a large data type and takes up a variable length of space, so the object is placed in the heap, but the object name is placed inside the stack, so that the object name can be used.

$p 1=new person ();
For this code, $p 1 is the object name in the stack memory, and the new person () is the real object in the heap memory.

Each instance object in the heap stores properties, for example, the instance object inside the heap now contains names, genders, and ages. Each property also has an address. $p 1=new person (); the right $p1 of the equals sign is a reference variable that assigns the first address of the object to the reference variable "$p 1" through the assignment operator "=", so $P1 is the variable that stores the first address of the object, $p 1 is placed in the stack memory, $p 1 is equivalent to a pointer pointing to the object inside the heap, So we can manipulate the object by $P1 this reference variable, and we usually refer to it as an object.

How to use members in an object

There are two types of members in a PHP object that are member properties, and one is a member method. Object we can already declare, $p 1=new person (), how to use the members of the object? To access members of an object, you use a special operator, "-" to accomplish access to the object members:

Object, Properties $p 1->name; $p 2->age; $p 3->sex;

Object, Method $p 1->say (); $p 2->run ();

 Name= "Zhang San"; $p 1->sex= "male"; $p 1->age=20;//The following three lines are the properties of the Access $p1 object echo "P1 the name of the object is:". $p 1->name. "
The gender of the "; echo" P1 object is: ". $p 1->sex."
The age of the "; echo" P1 object is: ". $p 1->age."
";///The following two lines access the method $p1->say () in the $p1 object; $p 1->run ();//The following three lines are assigned to $P2 object Properties $p2->name= "John Doe"; $p 2->sex= "female"; $p 2->age=30;//The following three lines are properties that access $P2 objects echo " The name of the P2 object is: ". $p 2->name."
The gender of the "; echo" P2 object is: ". $p 2->sex."
The age of the "; echo" P2 object is: ". $p 2->age."
The following two lines access the methods in the $p2 object $p2->say (); $p 2->run ();//The following three lines are assigned to $p3 object property $p3->name= "Harry"; $p 3->sex= "male"; $p 3->age=  40; The following three lines are the properties that access the $p3 object echo "The name of the P3 object is:". $p 3->name. "
The gender of the "; echo" P3 object is: ". $p 3->sex."
The age of the "; echo" P3 object is: ". $p 3->age."
";///The following two lines access the methods in the $p3 object $p3->say (); $p 3->run ();? >

As you can see from the example above, only the members of the object will be accessed using the object---Properties, Object-by-method, and there is no second way to access the members of the object.

Special reference to the use of "$this"

Now that we know how to access the members of the object, which is accessed through the object-to-member method, which is the form of accessing the members of the object outside of the object, if I want to let the object's methods access the properties of this object inside the object, Or the method in the object to invoke other methods of this object what do we do then? Because all the members of the object are to be called with objects, including the calls between the internal members of the object, in PHP, I provide a reference to this object $this, each object has a reference to the object $this to represent the object, to complete the invocation of the object's internal members, This is meant to mean "this", in the above example, we instantiate three instance objects $p1, $P 2, $P 3, three objects within each of the existence of a $this respectively represents the object $p1, $p 2, $p 3.

As we can see, the $this is the reference within the object that represents the object, and the same way that the members of the object are invoked inside the object and outside the member and object calling this object.

$this-Properties $this->name; $this->age; $this->sex;

$this-and Method $this->say (); $this->run ();

Modify the example above so that everyone speaks their name, gender and age:

 
  Name. "Gender:". $this->sex. "My Age is:" $this->age. "
";} function run ()//This person can walk the way {echo "This person is walking";}} $p 1=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 lines are assigned to the $p1 object property $p1->name= "Zhang San", $p 1->sex= "male", $p 1->age=20;//below to access $p1 object of speech method $p1->say ();/ The following three lines are assigned to the $p2 object property $p2->name= "John Doe", $p 2->sex= "female", and $p 2->age=30;//to access $p2 object's Speech method $p2->say ();//The following three lines are for $ P3 object property Assignment $p3->name= "Harry", $p 3->sex= "male", $p 3->age=40;//below to access $p3 object of speech method $p3->say (); >

Analyze This method:
function say ()//The way this person can speak
{
echo "My name is called:". $this->name. "Gender:" $this->sex. "My Age is:". $this->age. "
";
}
In the $P1, $p 2, and $p3 all three objects have say () This method, $this represent the three objects respectively, call the corresponding property, print out the value of the property, this is the way to access the object properties inside the object, if it is in the method of Say () called run () This method is also possible, In Say () This method uses $this->run () to complete the call.

Construction method and destructor method

Most classes have a special method called constructors. When an object is created, it automatically calls the constructor, which is automatically called when the object is instantiated using the New keyword.

The declaration of the constructor is the same as the declaration of the other operation, except that its name must be __construct (). This is a change in PHP5, in the previous version, the name of the constructor must be the same as the class name, which can still be used in PHP5, but is now used by very few people, the advantage is that the constructor is independent of the class name, when the class name changes, you do not need to change the corresponding constructor name. To be backwards compatible, if a class does not have a method named __construct (), PHP will search for a constructor in PHP4 that has the same name as the class name.

Only one construction method can be declared in a class, but a constructor is called every time the object is created, and the method cannot be invoked actively, so it is often used to perform some useful initialization tasks. For example, an attribute is assigned an initial value when creating an object.

 
  Name assigns the value $this->name= $name;//The $sex that is passed through the constructor method assigns the value $this->sex= to the member property $this->sex, or the $age to the member property by the constructor method This->age the value $this->age= $age;} This person's way of speaking function say () {echo "My name is called:". $this->name. "Gender:". $this->sex. "My Age is:". $this->age. "
";}} Create 3 objects by constructing the method $p1, P2, $p 3, passing in three different arguments for name, gender, and age $p1=new person ("Zhang San", "male"), $p 2=new person ("John Doe", "female"), $p 3=new Person ("Harry", "male", 40);//The following access to the $p1 object in the speech method $p1->say ();//The following access to the $p2 object in the speech method $p2->say ();//The following access to the $p3 object in the speech method $p3->say ();? >

A destructor is the opposite of a constructor function. Destructors are new additions to PHP5, and there are no destructors in PHP4. Destructors allow for some operations to be performed before destroying a class or to perform functions such as closing a file, releasing a result set, and so on, the destructor is removed from all references to an object or executed when the object is explicitly destroyed, that is, the object calls the destructor before it is destroyed in memory. Like the name of a constructor, a class's destructor name must be __destruct (). Destructors cannot have any parameters.

 
  Name assigns the value $this->name= $name;//The $sex that is passed through the constructor method assigns the value $this->sex= to the member property $this->sex, or the $age to the member property by the constructor method This->age the value $this->age= $age;} This person's way of speaking function say () {echo "My name is called:". $this->name. "Gender:". $this->sex. "My Age is:". $this->age. "
";} This is a destructor that calls function __destruct () {echo "Goodbye" before the object is destroyed. $this->name. "
”; }//creates 3 objects by constructing the method $p1, P2, $p 3, passing in three different arguments for name, gender and age $p1=new person ("Zhang San", "male"), $p 2=new person ("John Doe", "female", "X"), $p 3=new Person ("Harry", "male", 40);//The following access to the $p1 object in the speech method $p1->say ();//The following access to the $p2 object in the speech method $p2->say ();//The following access to the $p3 object in the speech method $p3->say ();? >

Encapsulation of

Encapsulation is one of the three characteristics of object-oriented programming, encapsulation is to combine the object's properties and services into a separate unit, and to conceal the inner details of the object as much as possible, including two meanings: 1. Combine all the properties of an object with all services to form an indivisible unit (i.e. object). 2. Information concealment, that is, as far as possible to conceal the internal details of the object, the external formation of a boundary (or form a barrier), only a limited external interface to make it contact with the outside.

The principle of encapsulation in the software reflects that the requirements of the object beyond the arbitrary access to the object's internal data (attributes), thereby effectively avoiding the external error on its "cross-infection", so that software errors can be localized, greatly reducing the difficulty of error-checking and debugging.

Use an example to illustrate, if a person's object has attributes such as age and wages, such as the nature of personal privacy is not to let others feel free to obtain, if you do not use encapsulation, then others want to know can be obtained, but if you package on the other people will not be able to obtain the attributes of encapsulation, unless you say it yourself , otherwise there is no way for others to get it.

For example, personal computers have a password, do not want to let others random landing, in your computer copy and paste. There is a human object, height and age attributes, can only be to increase their own, can not let others arbitrarily assigned to the value and so on.

Use the Private keyword to encapsulate properties and methods:

Original member: Var $name;   The name of the Claimant Var $sex;    The gender Var $age of the claimant;    The declarator's age function run () {...} Changed to package form: private $name;          The name of the person using the private keyword to encapsulate the private $sex;      Use the Private keyword to encapsulate the person's gender $age;      Use the Private keyword to encapsulate a person's age private function run () {...}  Use the Private keyword to encapsulate a person's way of walking. Note: The original keyword "var" should be removed as long as there are other keywords in front of the member attribute.

By private, you can encapsulate a person's members (member properties and member methods). The members on the package cannot be accessed directly outside the class, only the object can be accessed internally;

A private member cannot be accessed externally, because a private member can only access itself within the object itself, for example, $p 1 The object itself wants to say his private property, and in Say () This method accesses the private property, which is possible. (No access control is added, default is public, accessible anywhere)

Because the constructor method is the default public method (the construction method is not set to private), it can be accessed outside the class so that the object can be created using the construction method, and the constructor is also the function inside the class, so you can use the constructor method to assign the initial value to the private property. The method of Say () is the default public, so you can also access it outside, and say his own private property.

From the above example, we can see that the private members can only be used within the class, not directly from the outside of the class access, but within the class is access to the inside, so sometimes we need to be outside the class to assign the private property and read out, that is, to provide some access to the outside of the class interface, The constructor method in the example above is a form of assignment, but the constructor is only assigned when the object is created, and if we already have an existing object and want to assign a value to the existing object, then if you also pass the value in the form of the constructor method, a new object is created. This is not an existing object. So we have to do some external access to the private properties of the interface, the purpose is to be able to change and access the value of the property in the case of the object exists, but note that only need to let the external change of the property to do so, do not want to let the outside access to the property is not to do such an interface, so that can achieve the All the functions are done by the object itself, to provide as few operations as possible outside.

http://www.bkjia.com/PHPjc/752520.html www.bkjia.com true http://www.bkjia.com/PHPjc/752520.html techarticle Object -oriented conceptual object-oriented programming (object oriented programming, OOP, object-oriented programming) is a computer programming architecture, and one of the basic principles of OOP is that computer programs are ...

  • Related Article

    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.