PHP basic tutorial 9 and objects

Source: Internet
Author: User
This section describes the composition of classes and objects-the creation of objects-the PHP garbage collection mechanism-$ this

Content described in this section
  • Class and object

  • Class Composition

  • Object creation

  • PHP garbage collection mechanism

  • $ This explanation

Preface

PHP is an object-oriented programming language. So what is object-oriented? Why should we be object-oriented? In our life, many things are objects, such as a cup or a box. they all have their own unique characteristics and they are objects. Our development in development is also object-oriented programming. Objects are all things that people need to study. from the simplest integer to the complex aircraft, they can all be seen as objects. We use object-oriented programming to enable us to see the problem comprehensively, and also facilitate data management and maintenance. in PHP, object-oriented programming can be divided into two categories: Model and, what is the relationship between the two created objects?

Class and object

Class and object: objects with the same features (data elements) and behaviors (functions) are abstracted as classes. Therefore, the object is abstracted as a class, and the class is embodied as an object. It can also be said that the instance of the class is an object, and the class is actually a data type.

That is to say, extracting the functions and features of an object to form a class is like extracting the model of a cup, and we can follow this model (that is, the class) create various cups (objects ).
How is a class defined? How is an object created?

Class Composition
 

The above is the basic structure of a class. next we will explain in detail the meaning of each part.

  • Class is a keyword and cannot be modified, indicating that it is a class.

  • Cat is the class name. the class name starts with an upper-case letter and is named in the hump.

Class attributes

Attribute: A member attribute is an integral part of a class. it is generally of the basic data type (integer, string, etc.), composite type (object, array), and resource type. For example, the public $ age of the cat class is defined as the member attribute.

It can be said that each class has an attribute, and the class attribute is a type of feature. for example, a cat can have a name, age, color, and other common characteristics of these cat classes. In a class, such features are called Attributes. of course, we can also define attributes. This depends on your needs.

The public attribute is a permission modifier, which will be explained later.

Member methods (functions)

In the code above, we can see that there are several functions in the class, which are the same as the previous functions, but there is a permission control character in front. It can also be called the member method. These member methods are the behavior actions in the class. for example, the cat class above has the behavior of sleeping and eating, of course, you can write its own behavior.

Syntax of the member method:

Access modifier function name (form parameter) {// function body; // return value ;}
  • There are three access modifiers (public, protected, and privte). The default value is public.

  • The rest is the same as the functions we have learned, including the call mechanism.

  • There can be multiple parameter lists, which can be any type

  • The return value of the method depends on the specific requirements.

  • The member method is defined in the class. if it is defined outside the class, it is not the behavior of this class.

Constructor

The preceding cat class has a method named-_ construct (). This is a constructor. So what is a constructor? The constructor is used to initialize the data when creating an object. for example, we want to directly give the cat name, age, and color when creating a cat object, you can use the constructor.

public function __construct($name,$age,$color){            $this-> name = $name;            $this-> age = $age;            $this-> color = $color;}

The constructor syntax is:

Public function _ construct (form parameter) {// function body}

For the construct method name_construct () of the constructor, this is a magic method, which is described later. In fact, there is also a way to write the constructor, the method name of the constructor is the class name:

public function Cat($name,$age,$color){}

The above constructor defines the method correctly, but we recommend that you use the magic method (_ construct () to think that when our class name changes, no need to modify.

Note:The class names in PHP are case-insensitive.But we still need to write it in case. At the same time, the constructor does not return values.

Note the following when constructing a function:

  • Only one constructor can exist in a class. this is mandatory.

  • The constructor is a systemAutomatic CallWe don't need to tune it ourselves.

  • If we do not define a constructor, the system uses a default constructor in the following format: public function

  • _ Construct () {}, so no matter whether we define the constructor or not, it has constructor.

The above three situations are the main contents of the class, and we will downgrade other situations in the class in the future.

Object creation

The class of the object created above already exists. how can I create an object?

Object creation method
$cat = new Cat();

The syntax for creating an object is:

$ Object name = new class name (parameter 1, parameter 2 );

The parameters in the brackets after the class name are passed to the class constructor. if The constructor does not have any parameters, you can leave it empty.

  • The naming conventions of objects are the same as those of common variables. you can use the hump or underline methods.

  • New is also a keyword and cannot be modified, indicating the newly created object.

The purpose of creating an object is to operate the object, and the operation object is the attributes and methods in the operation object.

Write the following code below the above class:

// Create an object and pass the three parameters to the constructor. $ Cat = new Cat ('floret ', 12, 'black'); // access the object's attributes through the object echo $ cat-> name; echo'
'; Echo $ cat-> age; echo'
'; Echo $ cat-> color; echo'
'; $ Cat-> sleep (); $ cat-> eat (); ...... result ...... Xiaohua 12black cat sleeping cat eating

The above object uses-> access attributes and methods.Note that there is no $ symbol before the attribute.

$ Object name-> attribute name = value; echo $ object name-> attribute name; '->' is called an object operator.

The above is the creation of objects and the most basic applications.

Object transfer type

When we assign the object value to another variable, is it a value transfer or a reference transfer?

// Create an object $ cat = new Cat ('floret ', 12, 'black'); $ cat1 = $ cat; // assign $ cat to $ cat1; $ cat1-> name = 'xiaobai'; // use the $ cat1 object to modify the object name. Echo $ cat1-> name; // output the name of the $ cat1 object. Echo'
'; Echo $ cat-> name; // output the name of the $ cat object ...... Result:

It may be a bit confusing here, isn't it a value transfer? How can I modify the attributes of an object ?,

In the above code, $ cat1 = $ cat is also a value transfer, but this value is the object'sReference(Object Identifier), that is, each variable containing the object holds the object reference, rather than copying the entire object.

As shown in the preceding figure, when $ cat is assigned to $ cat1, the object identifier (#1) is copied and assigned to $ cat1, in fact, they still point to the same data zone, so as long as one of them modifies the value, the other will change.

Object destruction

After using the object, we have determined that this object will not be used in the future. at this time, we canManualSo how can we destroy the object?

  1. When no variable points to an object, it will be destroyed, so we can set the object reference to null.

  2. Use the unset () function to destroy objects.

    // Create an object $ cat = new Cat ('floret ', 12, 'black'); $ cat-> sleep (); unset ($ cat ); $ cat-> sleep ();..... result ..... cat sleeping Notice: Undefined variable: cat in D: \ mywamp \ Apache24 \ htdocs \ zendstudio \ yunsuanfu \ object. php on line 27 Fatal error: Call to a member function sleep () on null in D: \ mywamp \ Apache24 \ htdocs \ zendstudio \ yunsuanfu \ object. php on line 27

    In fact, when a file is running, PHP will start the garbage collection mechanism to automatically recycle it. At this time, the object created in it will be automatically destroyed. So what is PHP's garbage collection mechanism?

PHP garbage collection mechanism

Garbage collection, as its name implies, is the time to start the garbage collection mechanism in the program:

  • In php, when an object points to it without any reference, it becomes a spam object, and php will start the garbage collector to destroy the object.

  • Before the program exits, php will also enable the garbage collector to destroy objects.

So what is the garbage collection mechanism?

The garbage collection mechanism is available only after php5. the garbage collection mechanism used before php5.3 is a simple "reference count", that is, each memory object is allocated with a counter, when the memory object is referenced by a variable, the counter + 1; when the variable reference is removed, the counter-1; when the counter = 0, it indicates that the memory object is not used, this memory object is destroyed and garbage collection is complete. However, at the beginning of PHP5.3, a new garbage collection mechanism was used to implement a complex algorithm based on reference counting, to detect the existence of reference rings in memory objects (mutual reference of objects) to avoid memory leakage.

$ This description

When writing the class constructor above, we can see that $ this is used in the function. What is $ this in the object-oriented model?

$ This is a mechanism used in the class to access itself. The system assigns $ this to each object, representing the current object. In general, $ this indicates the object that is called in the current environment.

  Name = $ name; $ this-> age = $ age; $ this-> color = $ color;} public function sleep () {echo 'cat sleep
';} Public function eat () {echo' cat dinner
';} // Output the cat's information public function info () {echo 'cat's name is '. $ this-> name. 'Age is '. $ this-> age. 'Color is '. $ this-> color ;}}// create an object $ cat = new Cat ('xiaohua ', 12, 'black'); $ cat-> info (); echo'
'; // Create another object and pass it to different attributes $ cat1 = new Cat ('White', 6, 'White '); $ cat1-> info ();..... result ..... the cat name is Xiaohua. The age is 12. the color is black. the cat name is white. The Age is 6. the color is white.

In the info () function of the above class, $ this is used to output different results for different objects, because $ this represents which object is called in different environments.

Class destructor

As we mentioned above, object destruction actually has a method in the class, which is automatically executed by the system when the object is destroyed. We call it an destructor.

Public function _ destruct () {echo $ this-> name. 'is destroyed
';}

Introduce the concept of Destructor in PHP5. The destructor will be deleted from all references to an object (no variables point to the object, and the object will be destroyed ).Before DestructionRun.

The main function of destructor is to release resources allocated to objects, such as database connections or opened files.

Its syntax is:

Function _ destruct () {// function body [releases resources, such as database connections, or opens files]}

Destructor are also automatically called by the system, so we do not need to call them by ourselves. But when weNot writtenThe system does not execute the destructor.

  Name = $ name; $ this-> age = $ age; $ this-> color = $ color;} public function sleep () {echo 'cat sleep
';} Public function eat () {echo' cat dinner
';} // Output the cat's information public function info () {echo 'cat's name is '. $ this-> name. 'Age is '. $ this-> age. 'Color is '. $ this-> color;} public function _ destruct () {echo $ this-> name. 'destroyed
';}} // Create an object $ cat = new Cat ('xiaohua', 12, 'black'); echo $ cat-> name; // output object name echo'
'; Unset ($ cat); // destroys an object. The system automatically calls the destructor ...... Result ...... the flower is destroyed.

When $ cat is destroyed, the destructor is automatically executed.

  • The Destructor is automatically executed before the object is destroyed and has no return value. Only one destructor can be added to a class.

  • The Destructor destroys resources created by an object, not the object itself. the object itself is destroyed by the garbage collection mechanism.

When multiple objects are created in a file, after the file is executed and the object is destroyed, the object is created and then destroyed, this principle and Stack principle are very much desired. they are advanced, backward, and foremost.

Summary

Through the above explanations of classes and objects, we can know the differences and relationships between classes and objects. Classes are abstract and represent a class of things, such as cats. Objects are specific, representing a specific thing. A class is an object template, and an object is an instance of a class. At the same time, the basic composition of the class should be mastered.

The above is the content of PHP basic tutorial 9 and other objects. For more information, see PHP Chinese network (www.php1.cn )!

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.