Usage of magic methods in PHP

Source: Internet
Author: User

Usage of magic methods in PHP

/** PHP treats all class Methods Starting with _ (two underscores) as magic methods. Therefore, when you define your own class methods, do not use _ as the prefix. ** // _ Tostring, _ set, _ GET _ isset (), and _ unset () /* The _ tostring method allows a class to decide how it will react when it is converted to a string. _ set () is run when writing data to inaccessible members. _ Get () is utilized for reading data from inaccessible members. _ isset () is triggered by calling isset () or empty () on inaccessible members. _ unset () is invoked when unset () is used on inacc Essible members. */class testclass {private $ DATA = array (); Public $ Foo; public function _ construct ($ Foo) {$ this-> Foo = $ Foo ;} public Function _ tostring () {return $ this-> Foo;} public function _ set ($ name, $ value) {echo "_ set, setting '$ name' to' $ value' \ n "; $ this-> data [$ name] = $ value;} public function _ Get ($ name) {echo "_ Get, getting '$ name' \ n"; if (array_key_exists ($ name, $ this-> da Ta) {return $ this-> data [$ name] ;}}/** as of PHP 5.1.0 */public function _ isset ($ name) {echo "_ isset, is '$ name' set? \ N "; return isset ($ this-> data [$ name]);}/** as of PHP 5.1.0 */public function _ unset ($ name) {echo "_ unset, unsetting '$ name' \ n"; unset ($ this-> data [$ name]);} $ OBJ = new testclass ('hello'); echo "_ tostring, $ OBJ \ n"; $ obj-> A = 1; echo $ obj->. "\ n"; var_dump (isset ($ obj-> A); unset ($ obj-> A); var_dump (isset ($ obj-> )); echo "\ n";/** output result: _ tostring, hello _ set, setting 'A 'to '1' _ Get, getting 'A' _ isset, is 'A' set? Bool (true) _ unset, unsetting 'A' _ isset, is 'A' set? Bool (false) ** // _ call _ callstatic/* Mixed _ call (string $ name, array $ arguments) Mixed _ callstatic (string $ name, array $ arguments) _ call () is triggered when invoking inaccessible methods in an object context. _ callstatic () is triggered when invoking inaccessible methods in a static context. the $ name argument is the name of the method being called. the $ arguments argument is an enumerated array containing the parameters passed to the $ name 'ed method. */class methodtest {public function _ call ($ name, $ arguments) {// Note: value of $ name is case sensitive. echo "_ call, calling object method '$ name '". implode (',', $ arguments ). "\ n";}/** as of PHP 5.3.0 */public static function _ callstatic ($ name, $ arguments) {// note: value of $ name is case sensitive. echo "_ callstatic, calling static method '$ name '". implode (',', $ arguments ). "\ n" ;}}$ OBJ = new methodtest; $ obj-> runtest ('in object context', 'param2', 'param3'); // methodtest :: runtest ('in static context'); // as of PHP 5.3.0echo "\ n";/** the output result is as follows: _ call, calling object method 'runtest' in object context, param2, param3 string (10) "_ invoke: "* // _ invoke/* The _ invoke method is called when a script tries to call an object as a function. note: This feature is available since PHP 5.3.0. */class callableclass {function _ invoke ($ X) {var_dump ($ X) ;}}$ OBJ = new callableclass; // $ OBJ (5 ); var_dump ('_ invoke :'. is_callable ($ OBJ); echo "\ n"; // _ sleep _ wakeup/* serialize can include objects and convert them into continuous bytes data. you can save serialized variables in a file or transmit them over the network. then, the data is deserialized and restored to the original data. PHP can successfully store the attributes and methods of the objects defined before the objects of the deserialization class. sometimes you may need an object to be executed immediately after deserialization. for this purpose, PHP will automatically find the _ sleep and _ wakeup methods. when an object is serialized, PHP calls the _ sleep method (if any ). after an object is deserialized, PHP calls the _ wakeup method. both methods do not accept parameters. the _ sleep method must return an array containing the attributes to be serialized. PHP will discard other attribute values. if the _ sleep method is not available, PHP will save all attributes. the following example shows how to serialize an object using the _ sleep and _ wakeup methods. the ID attribute is a temporary attribute not intended to be retained in the object. the _ sleep method ensures that the ID attribute is not included in the serialized object. when a user object is deserialized, The __wakeup method creates a new value for the ID attribute. this example is designed to be self-sustaining. in actual development, you may find that objects containing resources (such as resources or data streams) need these methods */class user {public $ name; Public $ ID; function _ construct () {// give user a unique ID assign a different ID $ this-> id = uniqid ();} // _ sleep the returned value type is an array, the value in the array is the ID function _ sleep () of the field that does not need to be serialized () {// do not serialize this-> ID is not serialized ID return (Array ("name");} function _ wakeup () {// give user a unique ID $ this-> id = uniqid () ;}// create object sets up a device $ u = new user; $ U-> name = "Leon"; // serialize it serializization pay attention to the non-serialized ID attribute, and the id value is abandoned $ S = serialize ($ U ); echo "_ sleep, _ wakeup, S: $ s"; // the ID of the unserialize it deserialization is assigned a new value $ U2 = unserialize ($ S ); // $ U and $ U2 have different IDs $ U idprint_r ($ U); print_r ($ U2); echo "\ n "; /** the output result is as follows: _ sleep, _ wakeup, S: O: 4: "user": 1: {s: 4: "name"; s: 4: "Leon";} user object ([name] => Leon [ID] => 4db1b17640da1) user object ([name] => Leon [ID] => 4db1b17640dbc) * // _ set_state/* This static method is called for Classes exported by var_export () Since PHP 5.1.0. the only parameter of this method is an array containing exported properties in the form array ('properties' => value ,...). */Class A {public $ var1; Public $ var2; public static function _ set_state ($ an_array) {// as of PHP 5.1.0 // $ an_array the output is an array, instead of the print_r ($ an_array) object passed during the call; $ OBJ = new A; $ obj-> var1 = $ an_array ['var1']; $ obj-> var2 = $ an_array ['var2']; return $ OBJ; }}$ A = new A; $ A-> var1 = 5; $ A-> var2 = 'foo'; echo "_ set_state: \ n"; EVAL ('$ B = '. var_export ($ A, true ). ';'); // $ B = A :__ set_state (Array (// 'var1' => 5, // 'var2' => 'foo ', //); var_dump ($ B); echo "\ n";/** the output result is as follows: _ set_state: array ([var1] => 5 [var2] => Foo) object (a) #5 (2) {["var1"] => int (5) ["var2"] => string (3) "foo"} * // _ cloneclass subobject {static $ instances = 0; Public $ instance; public Function _ construct () {$ this-> instance = ++ self: $ instances;} public function _ clone () {$ this-> instance = + self: $ instances;} class mycloneable {public $ object1; Public $ object2; function _ clone () {// force a copy of this-> object, otherwise // it will point to same object. $ this-> object1 = clone $ this-> object1; }}$ OBJ = new mycloneable (); $ obj-> object1 = new subobject (); $ obj-> object2 = new subobject (); $ obj2 = clone $ OBJ; print ("_ clone, original object: \ n"); print_r ($ OBJ ); print ("_ clone, cloned object: \ n"); print_r ($ obj2); echo "\ n";/** the output result is as follows: _ clone, original object: mycloneable object ([object1] => subobject object ([instance] => 1) [object2] => subobject object ([instance] => 2 )) _ clone, cloned object: mycloneable object ([object1] => subobject object ([instance] => 3) [object2] => subobject object ([instance] => 2 ))*/

 

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.