Important knowledge points in PHP object-oriented language (2) _ PHP Tutorial

Source: Internet
Author: User
Important knowledge points of PHP object-oriented (2 ). 1. _ toString: when an object is printed, if this method is defined by this class, the return value of this method is printed; otherwise, the result is printed based on the default PHP behavior. This method is similar to 1. _ toString in Java:

When an object is printed, if the class defines this method, the return value of this method is printed; otherwise, the result is printed according to the default PHP behavior. This method is similar to toString () in Java ().

Class TestClass {

Public function _ toString (){

Return "This is TestClass ::__ toString. \ n ";

}

}

$ TestObj = new TestClass ();

Print $ testObj;

The running result is as follows:

Stephen-Air: Desktop $ php Test. php

This is TestClass ::__ toString.

2. _ get and _ set:

These two methods are used to process undeclared attribute access in the class. When an object user attempts to access an undeclared object property, __get () is called with a string containing the attribute name to be accessed as a parameter. No matter what is returned from the _ get () method, it is directly returned to the caller, just as the property with this value exists. In addition, if the attribute exists but its access visibility is private or protected, the two blocking methods will also be called. Otherwise, if the attribute exists and is accessible, you can directly access the attribute. These two methods will no longer be called. The following is an example code of the _ get () interception method:

Class TestClass {

Private $ privateField;

Public $ publicField;

Public function _ construct (){

$ This-> privateField = "This is a private Field. \ n ";

$ This-> publicField = "This is a public Field. \ n ";

}

Public function _ get ($ property ){

Print "_ get () is called. \ n ";

$ Method = "get $ {property }";

If (method_exists ($ this, $ method )){

Return $ this-> $ method ();

}

Return "This is undefined field. \ n ";

}

Public function getPrivateField (){

Return $ this-> privateField;

}

}

$ TestObj = new TestClass ();

Print $ testObj-> privateField;

Print $ testObj-> undefinedField;

Print $ testObj-> publicField;

The running result is as follows:

Stephen-Air: Desktop $ php Test. php

_ Get () is called.

This is a private Field.

_ Get () is called.

This is undefined field.

This is a public Field.

The rules called by the _ set () method are basically the same as those called by the _ get () method. The difference is that they are used to intercept value assignment operations for undefined or invisible class attributes. In addition, this method receives two parameters: the property name and the value to be set. See the following sample code:

Class TestClass {

Private $ privateField;

Public $ publicField;

Public function _ construct (){

$ This-> privateField = "This is a private Field. \ n ";

$ This-> publicField = "This is a public Field. \ n ";

}

Public function _ get ($ property ){

Print "_ get () is called. \ n ";

$ Method = "get $ {property }";

If (method_exists ($ this, $ method )){

Return $ this-> $ method ();

}

Return "This is an undefined field. \ n ";

}

Public function _ set ($ property, $ value ){

Print "_ set is called. \ n ";

$ Method = "set $ {property }";

If (method_exists ($ this, $ method )){

$ This-> $ method ($ value );

} Else {

Print "This is an undefined field. \ n ";

}

}

Public function getPrivateField (){

Return $ this-> privateField;

}

Public function setPrivateField ($ value ){

$ This-> privateField = $ value;

}

}

$ TestObj = new TestClass ();

$ TestObj-> privateField = "This is a private Field after set. \ n ";

$ TestObj-> undefinedField = "This is a undefined Field after set. \ n ";

$ TestObj-> publicField = "This is a public Field after set. \ n ";

Print $ testObj-> privateField;

Print $ testObj-> undefinedField;

Print $ testObj-> publicField;

The running result is as follows:

Stephen-Air: Desktop $ php Test. php

_ Set is called.

_ Set is called.

This is an undefined field.

_ Get () is called.

This is a private Field after set.

_ Get () is called.

This is an undefined field.

This is a public Field after set.

3. _ isset and _ unset:

The rules used to call these two interception methods are very similar to _ get () and _ set (). they are only used for non-existent or invisible attributes in the class and are isset () and unset () the two global method applications are triggered separately.

Class TestClass {

Private $ privateField;

Public $ publicField;

Public function _ construct (){

$ This-> privateField = "Defined private field ";

$ This-> publicField = "Defined public field ";

}

Public function _ isset ($ property ){

Print "_ isset is called. \ n ";

Return isset ($ this-> $ property );

}

Public function _ unset ($ property ){

Print "_ unset is called. \ n ";

If (isset ($ this-> $ property )){

Unset ($ this-> $ property );

}

}

}

$ TestObj = new TestClass ();

Print 'isset ($ testObj-> privateField) is '. (isset ($ testObj-> privateField )? "True": "false"). "\ n ";

Print 'isset ($ testObj-> undefinedField) is '. (isset ($ testObj-> undefinedField )? "True": "false"). "\ n ";

Print 'isset ($ testObj-> publicField) is '. (isset ($ testObj-> publicField )? "True": "false"). "\ n ";

Print "After unset... \ n ";

// After the following two functions are called, both the object attributes of $ testObj become unavailable.

// In addition, the __unset method is called only once. because publicField is a visible attribute, _ unset is not called because of this attribute.

Unset ($ testObj-> privateField );

Unset ($ testObj-> publicField );

Print 'isset ($ testObj-> privateField) is '. (isset ($ testObj-> privateField )? "True": "false"). "\ n ";

Print 'isset ($ testObj-> publicField) is '. (isset ($ testObj-> publicField )? "True": "false"). "\ n ";

The running result is as follows:

Stephen-Air: Desktop $ php Test. php

_ Isset is called.

Isset ($ testObj-> privateField) is true

_ Isset is called.

Isset ($ testObj-> undefinedField) is false

Isset ($ testObj-> publicField) is true

After unset ......

_ Unset is called.

_ Isset is called.

Isset ($ testObj-> privateField) is false

_ Isset is called.

Isset ($ testObj-> publicField) is false

4. _ call:

The _ call () method is a very useful but abuse-prone interception method. When the object user attempts to access the undefined member functions of the current object, __call () is automatically called and two parameters are passed at the same time, they are the function name and all parameters (arrays) passed to the called function ). Any value returned by the _ call method is returned to the function caller, just as the member function actually exists. The following is a very useful example of delegation.

Class DelegateClass {

Function printMessage ($ arg1, $ arg2 ){

Print "DelegateClass: delegatedMethod is called. \ n ";

Print '$ arg1 ='. $ arg1. 'and $ arg2 ='. $ arg2. "\ n ";

}

}

Class TestClass {

Private $ delegateObj;

Public function _ construct (){

$ This-> delegateObj = new DelegateClass ();

}

Public function _ call ($ method, $ args ){

$ This-> delegateObj-> $ method ($ args [0], $ args [1]);

}

}

$ TestObj = new TestClass ();

$ TestObj-> printMessage ("hello", "world ");

The running result is as follows:

Stephen-Air: Desktop $ php Test. php

DelegateClass: delegatedMethod is called.

$ Arg1 = helloand $ arg2 = world

From the above example, we can see that TestClass does not declare the printMessage member method, but it is passed directly to the delegate object through the clever bridge of _ call () method. I personally think this technique is a double-edged sword. do not over-use it.

5. callback function:

The application scenarios of callback functions do not need to be described. in C/C ++, there are countless typical use cases of callback functions. Here is a simple example of how to use callback functions in PHP. See the following sample code and Key notes:

Class Product {

Public $ name;

Public $ price;

Public function _ construct ($ name, $ price ){

$ This-> name = $ name;

$ This-> price = $ price;

}

}

Class ProcessSale {

Private $ callbacks;

Function registerCallback ($ cb ){

If (! Is_callable ($ cb )){

Throw new Exception ("callback not callable .");

}

$ This-> callbacks [] = $ cb;

}

Function sale ($ product ){

Print "{$ product-> name}: processing \ n ";

Foreach ($ this-> callbacks as $ cb ){

// You can call either of the following methods.

Call_user_func ($ cb, $ product );

$ Cb ($ product );

}

}

}

$ Logger = function ($ product ){

Print "logging ({$ product-> name}) \ n ";

};

$ Processor = new ProcessSale ();

$ Processor-> registerCallback ($ logger );

$ Processor-> sale (new Product ("shoes", 6 ));

Print "\ n ";

$ Processor-> sale (new Product ("coffee", 6 ));

The running result is as follows:

Stephen-Air: Desktop $ php Test. php

Shoes: processing

Logging (shoes)

Logging (shoes)

Coffee: processing

Logging (coffee)

Logging (coffee)

6. use (closure ):

There are a large number of closure applications in Javascript, while closures in PHP are completed by using the use keyword. For the concept of closure itself, simply put, the code in the function can access the variables in its parent scope. See the following sample code and Key notes:

Class Product {

Public $ name;

Public $ price;

Public function _ construct ($ name, $ price ){

$ This-> name = $ name;

$ This-> price = $ price;

}

}

Class ProcessSale {

Private $ callbacks;

Function registerCallback ($ cb ){

If (! Is_callable ($ cb )){

Throw new Exception ("callback not callable .");

}

$ This-> callbacks [] = $ cb;

}

Function sale ($ product ){

Print "{$ product-> name}: processing \ n ";

Foreach ($ this-> callbacks as $ cb ){

$ Cb ($ product );

}

}

}

Class Totalizer {

Static function warnAmount ($ amt ){

$ Count = 0;

// Note that both $ amt and $ count are closure variables, where & $ count is passed as a reference, that is, once the value of this variable is modified inside the function,

// When you access the closure variable again next time, $ count is the modified value in the previous call.

Return function ($ product) use ($ amt, & $ count ){

$ Count + = $ product-> price;

Print "count: $ count \ n ";

If ($ count> $ amt ){

Print "high price reached: {$ count} \ n ";

}

};

}

}

$ Processor = new ProcessSale ();

$ Processor-> registerCallback (Totalizer: warnAmount (8 ));

$ Processor-> sale (new Product ("shoes", 6 ));

$ Processor-> sale (new Product ("coffee", 6 ));

The running result is as follows:

Shoes: processing

Count: 6

Coffee: processing

Count: 12

High price reached: 12

Note: The points recorded in this Blog are some of the more unique PHP skills compared with other object-oriented languages, or, for me, I really need to write down the knowledge points for future reference. I hope to share it with you.

Http://www.bkjia.com/PHPjc/635016.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/635016.htmlTechArticle1. _ toString: when an object is printed, if this method is defined by the class, the return value of this method is printed; otherwise, the results are printed according to the default PHP behavior. This method is similar to Java...

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.