PHP Tutorial Magic Method Use Example (PHP magic function) _php Tutorial

Source: Internet
Author: User
Copy CodeThe code is as follows:
/** PHP treats all class methods starting with __ (two underscores) as a magic method. So when you define your own class method, do not prefix __. * */

__tostring, __set, __get__isset (), __unset ()
/*
The __tostring method allows a class to decide how it would react when it was converted to a string.
__set () is the run when writing the data to inaccessible members.
__get () is utilized for reading data from inaccessible.
__isset () is triggered by calling isset () or empty () on inaccessible members.
__unset () was invoked when unset () was 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->a));
unset ($obj->a);
Var_dump (Isset ($obj->a));
echo "\ n";
/**
The output results are 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 if invoking inaccessible methods in an object context.
__callstatic () is triggered if invoking inaccessible methods in a static context.
The $name argument is the name of the the method being called.
The $arguments argument is a 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 results are as follows:
__call, calling object method ' Runtest ' in object context, param2, param3
String ("__invoke:")
*/

__invoke
/*
The __invoke method is called if 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
/*
Serialization serialize can convert variables including objects into continuous bytes data. You can either have a serialized variable in a file or transfer it over the network.
Then crossdress the rows to revert to the original data. The classes that you define before you crossdress the objects of the class, PHP can successfully store the properties and methods of its objects.
Sometimes you may need an object to be executed immediately after the crossdress is serialized. For this purpose, PHP will automatically look for __sleep and __wakeup methods.
When an object is serialized, PHP invokes the __sleep method (if one exists). After crossdress an object, PHP calls the __wakeup method.
Both methods do not accept parameters. The __sleep method must return an array containing the properties that need to be serialized. PHP discards the values of other properties.
If there is no __sleep method, PHP will save all properties. The following example shows how to serialize an object using the __sleep and __wakeup methods.
The id attribute is a temporary property that is not intended to be persisted in the object. The __sleep method guarantees that the ID attribute is not included in the serialized object.
When crossdress a user object, the __wakeup method establishes the new value of the id attribute. This example is designed to be self-sustaining.
In real-world development, you may find that objects that contain resources (like or data streams) require these methods
*/

Class User {

Public $name;
public $id;

function __construct () {
Give User a unique ID is given a different ID
$this->id = Uniqid ();
}

__sleep the type of the return value is an array, the value in the array is the field ID that does not require serialization

function __sleep () {
Do not serialize This->id no serialization ID
Return (Array ("name"));
}

function __wakeup () {
Give User a unique ID
$this->id = Uniqid ();
}

}

Create object to set up a device
$u = new User;
$u->name = "Leon"; Serialize it serialization note the non-serialized ID attribute, the value of the ID is discarded
$s = serialize ($u);
echo "__sleep, __wakeup, S: $s"; Unserialize it crossdress the row ID is re-assigned
$u 2 = unserialize ($s); $u and $u 2 have different IDs $u and $u2 different IDs
Print_r ($u);
Print_r ($u 2);
echo "\ n";
/**
The output results are 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 was called for classes exported by Var_export () since PHP 5.1.0.
The only parameter of this method is a array containing exported properties in the form array (' properties ' = = value,: .).
*/

Class A {

public $var 1;
Public $var 2;

public static function __set_state ($an _array) {//As of PHP 5.1.0
$an _array print out an array instead of the object passed at the time of the call
Print_r ($an _array);
$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 results are 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 $object 1;
Public $object 2;

function __clone () {
Force a copy of This->object, otherwise
It'll point to same object.
$this->object1 = Clone $this->object1;
}

}

$obj = new Mycloneable ();
$obj->object1 = new Subobject ();
$obj->object2 = new Subobject ();
$obj 2 = Clone $obj;
Print ("__clone, Original object:\n");
Print_r ($obj);
Print ("__clone, Cloned object:\n");
Print_r ($obj 2);
echo "\ n";
/**
The output results are 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
))
*/

http://www.bkjia.com/PHPjc/733408.html www.bkjia.com true http://www.bkjia.com/PHPjc/733408.html techarticle Copy the code code as follows:/** PHP treats all class methods that begin with __ (two underscore) as a magic method. So when you define your own class method, do not prefix __. * */ //...

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