PHP Basic Tutorial IX and the like object

Source: Internet
Author: User

What this section explains

    • Classes and objects

    • Composition of the class

    • Creation of objects

    • PHP garbage collection mechanism

    • $this explanation

Objective

PHP is an object-oriented programming language, so what is object-oriented? Why should we target objects? There are many things in our life that are objects, such as a cup, a box, and so on, all of which have their own unique characteristics, which are objects. and our development in development is also object-oriented programming. Objects are anything that people want to study, from the simplest integers to complex airplanes, to be considered objects. We use object-oriented programming can let us see the problem can be seen comprehensively, but also conducive to the management and maintenance of data, in PHP, object-oriented can be two kinds of objects, a kind of mold, the creation of object use, a class of objects, using the mold created up, then they two what is the relationship?

Classes and objects

Classes and objects: abstractions of objects that have the same attributes (data elements) and behaviors (functions) are classes. Thus, an object's abstraction is a class, the materialization of a class is an object, or an instance of a class is an object, and a class is actually a data type.

In other words, the function and features of the object are extracted, forming a class, like the model of a cup extracted, and we can according to this model (that is, the class) to create a variety of cups (i.e. objects).
So what is the definition of the class? How are objects created?

The composition of the class

<?php    class cat{//Defines a cat public        $name;//Cat's name public        $age;//Cat's name public        $color;//Cat color        // How to construct a cat public        function __construct () {        } public        function sleep () {            echo ' cat sleeps ';        }        Public function Eat () {            echo ' cat eats ';        }    }

Above is the basic structure of a class, below we explain in detail the meaning of each part.

    • Class is a keyword and cannot be modified to indicate that it is a class.

    • Cat is the class name, the class name is the beginning of capital letters, the hump named.

Properties of the class

Property: A member property is a component of a class, typically a basic data type (integer, String, and so on), but also a composite type (object, array), resource type. For example, the public $age we defined earlier in the Cat category is a member property.

It can be said that each class has attributes, class properties are a class of characteristics, such as cats can have names, age, color, and so on, these cat common characteristics. This feature in a class is called a property, and of course we can not define the attribute. This to see their own needs.

The public in front of the property is a permission modifier, which is explained later.

Member Methods (functions)

As you can see in the code above, there are several functions in the class that are the same as the previous function, but one more permission control. It can also be called a member method, which is a behavior action in the class, such as the cat above, there is sleep this behavior, there is eating this behavior, of course, you can write it yourself what behavior.

Syntax for member methods:

Access modifier function  name (formal parameter) {    //function body;    return value;}
    • Access modifiers, three (public, protected, PRIVTE), default to public, followed by a detailed

    • The rest of the department is just like the function we learned, including the invocation mechanism.

    • Parameter list can have multiple, can be any type

    • For the return value of the method, this can be seen in the specific requirements.

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

constructor function

There is a method in the Cat class above, the method name is-__construct (), which is a constructor, what is a constructor? The constructor is the method of initializing the data when the object is created, such as when we want to give it the cat's name, age, and color directly when we create the Cat object, we can use the constructor.

Public function __construct ($name, $age, $color) {            $this, name = $name;            $this, age = $age;            $this, color = $color;}

The syntax of the constructor is:

Public  function  __construct (formal parameter) {      //function Body}

For the constructor's method name __construct (), this is a magic method, in the following introduction, in fact, the constructor also has a way of writing, constructor method name is the name of the class:

Public Function Cat ($name, $age, $color) {}

The above method of constructing methods is also correct, but it is recommended to use the Magic Method (__construct ()), so that when our class name changes, there is no need to modify.

Note that the names of classes in PHP are not case-sensitive , but we still want to write them by case. The constructor does not return a value at the same time.

The constructors need to be aware of:

    • In a class, there can be only one constructor, which is a mandatory requirement

    • Constructors are automatically called by the system, and we don't have to tune them ourselves.

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

    • __construct () {}, so whether or not we have a constructor defined, it has a constructor function.

The three cases above are the approximate contents of the class, and in the future we will drop other cases in the class.

Creation of objects

The class that created the object above already has, then how to create the object?

Object creation Methods

$cat = new Cat ();

The syntax for creating an object is:

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

The arguments in parentheses after the class name are passed to the constructor of the class, and if the constructor has no arguments, it can not be written.

    • The naming conventions for objects are like normal variables, and the use of hump or underline methods can

    • New is also a keyword that cannot be modified to represent a newly created object

The object that we create is to manipulate the object, and the object is the property and the method inside the object of the manipulation.

Under the above class, write the following code:

Creates an object, passing three arguments to the constructor. $cat = new Cat (' Floret ', ' n ', ' black ');//property accessed by Object echo $cat, Name;echo ' <br> '; Echo $cat-Age;echo ' <br> ", Echo $cat-Color;echo ' <br>", $cat, Sleep (), $cat-eat (); Results...... Small flower 12black cat sleeping cat Eating

The above objects are accessed through properties and methods. note The property does not have a $ symbol in front of it.

$ object Name, property name = value; echo  $ object Name, property name; ' ' is called an object operator.

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

The delivery type of the object

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

    Create an object    $cat = new Cat (' Floret ', ' n ', ' Black ');    $cat 1 = $cat; Assign $cat this object to $CAT1;    $cat 1, name = ' small white ';//use $CAT1 to modify the name of the object.    echo $cat 1, name;//output $CAT1 the names of the objects.    echo ' <br> ';    Echo $cat, name; The name of the output $cat object. ..... Results...... Small white small white

Is it possible to see a bit of a mask here, not a value pass? How can I change the properties of an object and change the other one? ,

In the above code $cat 1= $cat is also a value pass, but this value is a reference to the object (which can understand the object identifier), that is, each variable containing the object holds the object's reference, not a copy of the entire object.

As can be seen in the above figure, when $cat is assigned to $CAT1, that is, the object identifier (#1) copied a copy, assigned to $CAT1, in fact, they still point to the same block data area, so long as one of the modified value, the other one will change.

Destruction of objects

After we have used the object, we have determined that we will not use this object in the future, so we can destroy the object manually , so how do we get the object destroyed?

    1. When there is no variable pointing to the object, it is destroyed, so we can set the object reference to NULL

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

      Create an object $cat = new Cat (' Floret ', ' black '), $cat, Sleep (), unset ($cat), $cat, Sleep (), ... Results..... Cat sleeps notice:undefined variable:cat in D:\mywamp\Apache24\htdocs\zendstudio\yunsuanfu\object.php on line 27Fatal 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 runs out of time, PHP will start the garbage collection mechanism, automatic garbage collection. The object created in this case is automatically destroyed, so what is the garbage collection mechanism of PHP?

PHP garbage collection mechanism

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

    • In PHP, when an object does not have any references to it, it becomes a garbage object, and PHP launches the garbage collector to destroy the object.

    • PHP will also enable the garbage collector to destroy objects before the program exits.

So what is a garbage collection mechanism?

Garbage collection mechanism is php5 after, php5.3 used before the garbage collection mechanism is a simple "reference count", that is, each memory object is allocated a counter, when the memory object is referenced by a variable, counter +1; When the variable reference is removed, the counter-1; when the counter = 0 o'clock, Indicates that the memory object is not being used, the memory object is destroyed, and the garbage collection is complete. But PHP5.3, using a new garbage collection mechanism, based on reference counting, implements a complex algorithm to detect the existence of reference rings in memory objects (mutual references to objects) to avoid memory leaks.

$this description

When you write a constructor for a class, you can see that $this is used in the function, so what is $this in object-oriented?

$this is a mechanism for accessing itself that is used in a class. Each object is assigned a $this that represents the current object. Popularly speaking is in the current environment, who calls, $this on behalf of which object.

<?php    class cat{//Defines a cat public        $name;//Cat's name public        $age;//Cat's name public        $color;//Cat color        // Cat definition method Public        function Cat ($name, $age, $color) {            $this, name = $name;            $this, age = $age;            $this, color = $color;        }        Public Function Sleep () {            echo ' cat sleeps <br> ';        }        Public function Eat () {            echo ' cat eats <br> ';        }        Output Cat Information public        function info () {            echo ' cat's name is '. $this. ' Age is '. $this, age. ' Color is '. $this-color;        }    }    Create an object    $cat = new Cat (' Floret ', ' n ', ' Black ');    $cat-Info ();    Echo ' <br> ';    Create another object, pass in a different property    $cat 1 = new Cat (' Small white ', 6, ' Bai ');    $cat 1, info ();    ..... Results..... The name of the cat is Floret age is 12 color is black Cat's name is small white age is 6 color is whites

Using $this in the info () function in the above class, different objects output different results because, in different environments, who is called, $this represents which object.

Destructors for classes

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

Public Function __destruct () {        echo $this->name. ' Destroyed <br> ';}

The concept of destructors is introduced in PHP5, where all references to an object are deleted (no variables point to the object and are destroyed), and the object is executed before it is destroyed .

The main function of destructor is to release the related resources of object allocation, such as database connection or open file.

Its syntax is:

  functions __destruct () {    //function body [frees resources, such as database connections, or open files, etc.]}

Destructors are also automatically called by the system, and we don't have to tune them ourselves. But when we do not write destructors, the system does not perform destructors.

<?phpclass cat{//define a cat public    $name;//Cat's name public    $age;//Cat's name public $color;//cat    color    //Cat definition method Public    function Cat ($name, $age, $color) {        $this, name = $name;        $this, age = $age;        $this, color = $color;    }    Public Function Sleep () {        echo ' cat sleeps <br> ';    }    Public function Eat () {        echo ' cat eats <br> ';    }    Output Cat Information public    function info () {        echo ' cat's name is '. $this. ' Age is '. $this, age. ' Color is '. $this color;    }    Public Function __destruct () {        echo $this->name. ' Destroyed <br> ';    }} Create an object $cat = new Cat (' Floret ', ' n ', ' black '), Echo $cat, name; The name of the output object echo ' <br> '; unset ($CAT); Destroys the object and the system automatically calls the destructor. ..... Results...... Floret Small perianth destroyed

When we destroy the object $cat, the destructor is executed automatically.

    • Destructors are executed automatically before an object is destroyed, and it does not return a value. You can have only one destructor in a class.

    • Destructors are resources created by destroying objects, not destroying the objects themselves, and the objects themselves are destroyed by the garbage collection mechanism.

When we create more than one object in a file, when the file is executed, the object is destroyed, the object is created after the destruction, after the creation of the object, first destroyed, this principle and the principle of the stack is very much like, advanced after out, LIFO first.

Summarize

By explaining the classes and objects above, we can know the differences and connections between classes and objects. Classes are abstract and represent a class of things, such as cats. The object is specific and represents a specific thing. A class is a template for an object that is an instance of a class. At the same time the basic structure of the class to master.

The above is the basic PHP tutorial nine and other objects of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.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.