Examples of magic methods used in php tutorials (php magic functions)

Source: Internet
Author: User
This article describes how to use php magic methods (php magic functions). For more information, see

This article describes how to use php magic methods (php magic functions). For more information, see

The Code is as follows:


/** 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 inaccessible 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-> data )){
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-> a. "\ n ";
Var_dump (isset ($ obj-> ));
Unset ($ obj-> );
Var_dump (isset ($ obj-> ));
Echo "\ n ";
/**
The output result is as follows:
_ 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.0
Echo "\ 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 store serialized variables in a file or transmit them over the network.
Then the deserialization is restored to the original data. The class you defined before the object of the deserialization class can be successfully stored by PHP.
Sometimes you may need to execute an object immediately after deserialization. For this purpose, PHP will automatically find the _ sleep and _ wakeup methods.
When an object is serialized, PHP will call the _ sleep method (if any). After an object is deserialized, PHP will call the _ wakeup method.
Both methods do not accept the parameter. _ sleep method must return an array containing the serialized attribute. PHP will discard the values of other attributes.
Without the _ sleep method, 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-maintained.
In actual development, you may find that objects containing resources (such as or data streams) need these methods.
*/

Class User {

Public $ name;
Public $ id;

Function _ construct (){
// Assign a different ID to the give user a unique ID
$ This-> id = uniqid ();
}

// _ The type of the sleep returned value is array, and the value in the array is the id of the field that does not need to be serialized.

Function _ sleep (){
// 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 serialization pay attention to the non-serialized id attribute, and the id value is discarded
$ S = serialize ($ u );
Echo "_ sleep, _ wakeup, s: $ s"; // unserialize it deserialization id is re-assigned
$ U2 = unserialize ($ s); // $ u and $ u2 have different IDs $ u and $ u2 have different IDs.
Print_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 {

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 object passed during the call.
Print_r ($ an_array );
$ Obj = new;
$ Obj-> var1 = $ an_array ['var1'];
$ Obj-> var2 = $ an_array ['var2'];
Return $ obj;
}

}

$ A = new;
$ 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"
}
*/

// _ Clone
Class 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.