Important PHP object-oriented knowledge points (2)

Source: Internet
Author: User
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 toString () in Java (). Copy the code & lt ;? PhpclassTestClass {publicfunc... "/> <scripttype =" text/j 1. _ toString: when an object is printed, if this class defines this method, the return value of this method is printed; otherwise, the result is printed based on the default PHP behavior. This method is similar to toString () in Java (). Copy code 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; copy the code and run the following result: 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: Copy the code 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 (me Thod_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 s Et. \ n "; $ testObj-> publicField =" This is a public Field after set. \ n "; print $ testObj-> privateField; print $ testObj-> undefinedField; print $ testObj-> publicField; copy the code and run the following result: Copy the code: 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. replay Code 3. _ isset and _ unset: the rules for calling the two interception methods are very similar to those of _ get () and _ set, it is triggered only when the non-existent or invisible attribute in the class is applied by the isset () and unset () global methods. Copy code 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, the attributes of both objects 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"; copy the code and run the following result: Copy the code Stephen-Air: Desktop $ php Test. php _ isset is called. isset ($ testObj-> privateField) is true _ isset is called. isset ($ testObj-> undefinedField) is falseisset ($ testObj-> publicField) is trueAfter unset ...... _ unset is called. _ isset is called. isset ($ testObj-> privateField) is false _ isset is called. isset ($ testObj-> publicField) is false to copy code 4. the _ call: _ call () method is a very Useful but very vulnerable interception methods. 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. Copy code DelegateObj = new DelegateClass ();} public function _ call ($ method, $ args) {$ this-> delegateObj-> $ method ($ args [0], $ args [1]) ;}}$ testObj = new TestClass (); $ testObj-> printMessage ("hello", "world"); copy the code and run the following result: stephen-Air: Desktop $ php Test. php DelegateClass: delegatedMethod is called. $ arg1 = helloand $ arg2 = world as shown in the preceding example, TestClass does not declare the printMessage member method, but 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 functions: 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: Copy the code 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) {// either of the following call methods is acceptable. 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); copy the code and run the following: desktop $ php Test. php shoes: processing logging (shoes) coffee: proc Essing logging (coffee) copying code 6. use (closure): There are a large number of closure applications in Javascript, and 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: Copy the code 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); copy the code and run the following results: shoes: processing count: 6 coffee: processing cou Nt: 12 high price reached: 12 note: The Knowledge Point recorded in this Blog is when I learned PHP, some of the things that PHP has encountered are more unique than 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.

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.