The use of Magic methods in PHP

Source: Internet
Author: User
Tags bool mixed serialization unique id

The use of Magic methods in PHP

/** PHP treats all class methods that start with __ (two underscores) as magic methods. So when you define your own class method, don't prefix it with __. * */

__tostring, __set, __get__isset (), __unset ()

/*

The __tostring method allows a class to decide how it'll react when it's converted to a string.

__set () is the run when writing the members of the data to inaccessible.

__get () is utilized to reading data from inaccessible.

__isset () is triggered by calling isset () or empty () on the inaccessible members.

__unset () is invoked when unset () are 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, $objn";

$obj->a = 1;

Echo $obj->a. "NN";

Var_dump (Isset ($obj->a));

unset ($obj->a);

Var_dump (Isset ($obj->a));

echo "NN";

/**

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 when invoking inaccessible methods in the object context.

__callstatic () is triggered then invoking inaccessible methods in a static context.

The $name argument is the name of 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 the object context ', ' param2 ', ' param3 ');

Methodtest::runtest (' In the static context '); As of PHP 5.3.0

echo "NN";

/**

The output results are as follows:

__call, calling object method ' Runtest ' in the object context, param2, param3

String (a) "__invoke:"

*/

__invoke

/*

The __invoke method are 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 "NN";

__sleep __wakeup

/*

The serialized serialize can be used to convert variables including objects into continuous bytes data. You can either have the serialized variables in a file or transfer them over the network.

Then drag the row to revert to the original data. You drag the class defined before the object of the row class, PHP can successfully store its object's properties and methods.

Sometimes you may need an object to execute immediately after drag. For this purpose, PHP will automatically look for __sleep and __wakeup methods.

When an object is serialized, PHP invokes the __sleep method (if it exists). After drag an object, PHP invokes the __wakeup method.

Neither of these methods accepts parameters. The __sleep method must return an array containing the attributes that need to be serialized. PHP discards the values of other attributes.

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 property is a temporary property that is not intended to remain in the object. The __sleep method guarantees that no ID attribute is included in the serialized object.

When the drag rows a user object, the __wakeup method creates a new value for the id attribute. This example is designed to maintain itself.

In actual development, you may find that objects that contain resources, such as images or data streams, require these methods

*/

Class User {

Public $name;

public $id;

function __construct () {

Give User a unique ID given a different ID

$this->id = Uniqid ();

}

The type of the __sleep return value is an array, and the value in the array is a field ID that does not need to be serialized

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 id attribute is not serialized, the value of the ID is abandoned

$s = serialize ($u);

echo "__sleep, __wakeup, S: $s"; Unserialize It drag the row ID is assigned a value

$u 2 = unserialize ($s); $u and $u 2 have different IDs $u and $U2 with a different ID

Print_r ($u);

Print_r ($u 2);

echo "NN";

/**

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 is called to 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 (' property ' => value, ... .).

*/

Class A {

public $var 1;

Public $var 2;

public static function __set_state ($an _array) {//As of PHP 5.1.0

$an _array is printed out as an array, not as an object passed at call time

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 "NN";

/**

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 "NN";

/**

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

))

*/

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.