Examples of using the Magic method of the PHP tutorial

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

  This article mainly introduces the PHP magic method of using the example (PHP magic function), need friends can refer to the following

The   code is as follows:/** 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 w Ill 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;       P ublic function __construct ($foo) {        $this->foo = $foo;    }       Public Function __tostring () {        return $this->foo;    }       Publ IC function __set ($name, $value) {        echo __set, Setting ' $name ' to ' $value 'n ";         $this->data[$name] = $value;    }       public Function __get ($name) {        echo "__get, getting" $nam E ' n ';         if (array_key_exists ($name, $this->data)) {            Retur n $this->data[$name];        }     {     /** as of PHP 5.1.0 *     Public Function __ Isset ($name) {        echo "__isset, is ' $name ' set?n ';         return Isset ($thi s->data[$name]);    }      /** as of PHP 5.1.0/    Public Function __unset ($name) {    & nbsp   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"; /**   output results are as follows:   __tostring, Hello   __set, Setting ' a ' to ' 1 '   __get, getting ' a ' &n Bsp __isset, is ' a ' set?   BOOL (true)   __unset, unsetting ' a '   __isset, is ' a ' set?   BOOL (false)  **/     //__call  __callstatic/*   mixed __call (string $name, arr Ay $arguments)   mixed __callstatic (string $name, array $arguments)   __call () is triggered when invoking I Naccessible methods in the object context.   __callstatic () is triggered when invoking inaccessible methods into 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, $argu ments) {       //Note:value of $name is case sensitive.         Echo __callst Atic, 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"; /**   output results are as follows:  __call, calling object method ' Runtest ' in the object context, par AM2, Param3   String (a) "__invoke:"  */     /__invoke/*    The __invoke method I s 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) {    &nbsP   Var_dump ($x);    }}   $obj = new Callableclass; $obj (5); Var_dump (' __invoke: ' Is_callable ($obj)); echo "nn";           //__sleep  __wakeup/*   Serialization serialize can convert variables including objects into continuous bytes data . You can either have the serialized variable in a file or transfer .    on the network and then revert to the original data drag the row. 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 calls the __wakeup method .    Neither method accepts arguments. The __sleep method must return an array containing the attributes that need to be serialized. PHP discards the value 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 attributes are included in the serialized object .    When drag rows a user object, the __wakeup method creates a new value for the id attribute. This example is designed to maintain .    in actual development, you may find that objects containing resources (such as images or data streams) need these methods  */  class User {      public $na Me     public $id;       function __construct () {       //give User A unique ID gives a different ID         $this->id = Uniqid ();    }      //__sleep The type of the return value is an array, and the value in the array is the 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   &NBS P     $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 row ID is $u 2 = unserialize ($s); $u and $u 2 have different IDs $u and $U2 have differentiated ID print_r ($U); Print_r ($u 2); echo "nn"; /**   output results are as follows:   __sleep, __wakeup, S:o:4: "User": 1:{s:4: "Name"; s:4: "Leon";}   User Object & nbsp (  [name] => Leon   [id] => 4db1b17640da1  )   User Object   (&nbsP [Name] => Leon   [id] => 4db1b17640dbc    */   //__set_state *   This static met Hod is called to classes exported by Var_export () since PHP 5.1.0.   The only parameter to this method is a array containing exported properties in the form array (' property ' => val UE, ...).  */  class A {      public $var 1,     public $var 2,       public Stati C function __set_state ($an _array) {/As of PHP 5.1.0        //$an _array print out is an array, not an object that is passed when invoked   & nbsp     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"; /**   output results are as follows:   __set_state:   Array   (  [var1] => 5   [var2] => fo o  )   object (A) #5 (2) {  ["var1"]=>   int (5)   ["Var2"]=>   string (3) "Foo"    */     //__clone class Subobject {      static $instances = 0;     Pub LIC $instance;       Public Function __construct () {        $this->instance = ++self:: $instances;    }       public Function __clone () {      $this->instance = ++self:: $instances;    }  }   class Mycloneable {      public $object 1,     public $object 2; & nbsp     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"; /**   Output results are as follows:  __clone, Original object:   Mycloneable object   (  [Object1] => subobject obje CT   (  [instance] => 1  ) [Object2] => subobject Object   (  [instance] => 2   )   __clone, cloned object:   Mycloneable object   (  [Object1] => subobject Object   (&nbs P [Instance] => 3   [object2] => subobject Object   (  [instance] => 2  ))    */& nbsp
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.