Important knowledge points in PHP object-oriented (ii) _php tutorial

Source: Internet
Author: User
1. __tostring: When the object is printed, if the class defines the method, the return value of the method is printed, otherwise the print result is printed according to the default behavior of PHP. This method is similar to ToString () in Java. Copy Code Privatefield = "This is a private field.\n"; $this->publicfield = "This was a public field.\n"; The Public Function __get ($property) {print ' __get () is called.\n "; $method =" Get${property} "; if (Method_exists ($this, $m Ethod) {return $this $method ();} return "This is undefined field.\n"; } public Function Getprivatefield () {return $this->privatefield;}} $TESTOBJ = new TestClass ();p rint $testObj->privatefield;print $testObj->undefinedfield;print $testObj Publicfield; The copy code runs as follows: stephens-air:desktop$ PHP test.php __get () is called. This was a private field.__get () is called. This is undefined field. This was a public Field. The __set () method is called with the same rules as __get (), which are used to intercept assignment operations for undefined or invisible class properties. In addition, the method receives two parameters, namely the attribute name and the value to be set. See the following code example: copying code Privatefield = "This is a private field.\n"; $this->publicfield = "This was a public field.\n"; The Public Function __get ($property) {print ' __get () is called.\n "; $method =" Get${property} "; if (Method_exists ($this, $m Ethod) {return $this $method ();} return "This was an undefined field.\n"; The Public Function __set ($property, $value) {print "__set is called.\n"; $method = "Set${property}"; if (Method_exists ($th is, $method)) {$this-$method ($value);} else {print "This was an undefined field.\n";}} Public Function Getprivatefield () {return $this->privatefield;} public Function Setprivatefield ($value) {$this Privatefield = $value; }} $TESTOBJ = new TestClass (); $TESTOBJ->privatefield = "This was a private Field after set.\n"; $TESTOBJ->undefinedfie LD = "This was a undefined field after set.\n"; $TESTOBJ->publicfield = "The is a public field after set.\n"; Print $TESTOBJ->privatefield;print $testObj->undefinedfield;print $testObj->publicfield; Copy code to run the knotThe following: Copy code stephens-air:desktop$ PHP test.php __set is Called.__set is called. This is a undefined field.__get () is called. This was a private Field after Set.__get () is called. This was an undefined field. This was a public Field after set. Copy Code 3. __isset and __unset: These two interception methods are called by the same rules as __get () and __set (), and are only triggered when they are applied to the non-existent or invisible properties of the class in the two global methods of Isset () and unset (). Copy Code Privatefield = "Defined private field"; $this->publicfield = "Defined public field"; The 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 ();p rint ' isset ($testObj->privatefield) is '. (Isset ($testObj->privatefield)? "True": "false"). " \ n ";p rint ' isset ($testObj->undefinedfield) is '. (Isset ($testObj->undefinedfield)? "True": "false"). " \ n ";p rint ' isset ($testObj->publicfield) is '. (Isset ($testObj->publicfield)? "True": "false"). " \ n "; Print "After unset......\n", or//After two function calls, the two object properties $TESTOBJ will become unavailable. Also from the output, the __unset method is called only once, because Publicfield is a visible property, so __unset is not called because of this property. unset ($TESTOBJ->privatefield); unset ($TESTOBJ->publicfield); print ' Isset ($testObj->privatefield) is '. (Isset ($testObj->privatefield)? "True": "false"). " \ n ";p rint ' isset ($testObj->pubLicfield) is '. (Isset ($testObj->publicfield)? "True": "false"). " \ n "; The copy code runs as follows: Copy code stephens-air:desktop$ PHP test.php __isset is called.isset ($testObj->privatefield) is true__ Isset is Called.isset ($testObj->undefinedfield) are Falseisset ($TESTOBJ->publicfield) is Trueafter unset......__ Unset is Called.__isset-Called.isset ($TESTOBJ->privatefield) is False__isset ($TESTOBJ- Publicfield) is false copy code 4. __call: The __call () method is a very useful but very easy to use interception method. When an object consumer attempts to access a member function that is not defined by the current object, __call () is automatically called, passing two parameters, each of which is the function name and all arguments (arrays) passed to the calling function. Any value returned by the __call method is returned to the function caller as if the member function were real. A very useful example of a delegate is given below. Copy Code Delegateobj = new Delegateclass (); The Public Function __call ($method, $args) {$this->delegateobj-> $method ($args [0], $args [1]);}} $TESTOBJ = new TestClass (); $TESTOBJ->printmessage ("Hello", "World"); The copy code runs the following result: stephens-air:desktop$ PHP test.php Delegateclass:delegatedmethod is called. $arg 1 = helloand $arg 2 = World as can be seen from the above example, TestClass does not declare a Printmessage member method, but through __ The smart bridging of the call () method is passed directly to the delegate object. Personally, this technique is a double-edged sword, so do not overuse it. 5. Callback function: The application scenario of the callback function does not need to be described, and is flooded with numerous callback function typical use cases. This simply gives the rules for using the callback function in PHP. See sample code and key notes as follows: Copy 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) {//The following two call methods are Can Call_user_func ($CB, $product); $CB ($product); }}} $logger = function ($product) {print "Logging ({$product->name}) \ n";}; $processor = new Processsale (), $processor->registercallback ($logger), $processor->sale ("Shoes", 6) ;p rint "\ n"; $processor->sale (New Product ("Coffee", 6)); The copy code runs as follows: Copy code stephens-air:desktop$ php test.php Shoes: Processing logging (shoes) logging (shoes) coffee:processing logging (coffee) logging (coffee) Copy code 6. Use (closures): There are a lot of closures in JavaScript, and closures in PHP are done using the USE keyword. For the concept of closures itself, it is simply that the code within the function can access the variables in its parent scope. See sample code and key notes as follows: Copy 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 ($produc T); }}}} class Totalizer {static function Warnamount ($amt) {$count = 0;//Note that the $amt and $count here are closed variables, where & $count is passed in the form of a reference, that is, once The value of the variable is modified inside the function//Then the next time you access the closure variable, the $count will be 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 copy code runs the following result: Shoes:processing Count:6coffee: Processing Count:12 High price reached:12 Note: The blog in the knowledge points recorded in the course of my study in PHP, encountered some of the phP is a bit more unique than other object-oriented languages, or a point of knowledge that I do need a book to write down for later. Although there is no depth, but still hope to share with you.

http://www.bkjia.com/PHPjc/635016.html www.bkjia.com true http://www.bkjia.com/PHPjc/635016.html techarticle 1. __tostring: When the object is printed, if the class defines the method, the return value of the method is printed, otherwise the print result is printed according to the default behavior of PHP. This method is similar to Java ...

  • 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.