Magic method in PHP (Magic methods) and solid magic

Source: Internet
Author: User
Tags export class

Php's method of starting with two underscores is called a magic method, which plays a pivotal role in PHP.     Magic methods include: __construct (), class constructor __destruct (), Class destructor __call (), call to an inaccessible method in an object when calling __callstatic (), invoking an inaccessible method in a static way __get (), gets a member variable of a class when called __set (), sets a member variable of a class when called __isset (), when calling Isset () or empty () on a non-accessible property call __unset () when calling unset () on an inaccessible property    ) is called. __sleep (), when executing serialize (), first calls the function __wakeup (), executes Unserialize (), first calls the function __tostring (), the class is treated as a string response method __invoke (), calls the function    This static method is called when an object is called in the way of a response method __set_state (), when the Var_export () export class is called. __clone (), calling __construct () and __destruct () constructors and destructors when the object is copied are not unfamiliar, they are called when objects are created and extinct. For example, we need to open a file, open when the object is created, close when the object dies<?PHPclassfileread{protected $handle=NULL; function__construct () {$this->handle =fopen(...); }    function__destruct () {fclose($this-handle); }}?>These two methods can be extended during inheritance, for example:<?PHPclassTmpfilereadextendsfileread{function__construct () {Parent::__construct (); }    function__destruct () {Parent::__destruct (); }}?>Both methods are called when __call () and __callstatic () call an inaccessible method in an object, which is a static method. These two methods may be used in the variable method (Variable functions) call. <?PHPclassMethodtest { Public function__call ($name,$arguments) {        Echo"Calling object Method"$name‘ ".implode(‘, ‘,$arguments). "\ n"; }     Public Static function__callstatic ($name,$arguments) {        Echo"Calling static Method"$name‘ ".implode(‘, ‘,$arguments). "\ n"; }}$obj=Newmethodtest;$obj->runtest (' in object context ')); Methodtest:: Runtest (' in static context ');?>__get (), __set (), __isset () and __unset () when Get/These two functions are called when a member variable of a class is set. For example, we save an object variable in another array, not the member variable of the object itself.<?PHPclassmethodtest{Private $data=Array();  Public function__set ($name,$value){        $this->data[$name] =$value; }     Public function__get ($name){        if(array_key_exists($name,$this-data)) return $this->data[$name]; return NULL; }     Public function__isset ($name){        return isset($this->data[$name])    }     Public function unset($name){        unset($this->data[$name]); }}?>__sleep () and __wakeup () when we execute serialize () and unserialize (), these two functions are called first. For example, when we serialize an object that has a database link that wants to restore the link state in deserialization, you can refactor the two functions to achieve a link recovery. Examples are as follows:<?PHPclassConnection {protected $link; Private $server,$username,$password,$db;  Public function__construct ($server,$username,$password,$db)    {        $this->server =$server; $this->username =$username; $this->password =$password; $this->db =$db; $this-Connect (); }    Private functionConnect () {$this->link =mysql_connect($this->server,$this->username,$this-password); mysql_select_db($this-&GT;DB,$this-link); }     Public function__sleep () {return Array(' Server ', ' username ', ' password ', ' db '); }     Public function__wakeup () {$this-Connect (); }}?>the __tostring () object is used as a string response method. For example, using the Echo$obj; To output an object<?PHP//Declare a simple classclasstestclass{ Public function__tostring () {return' This is a object '; }}$class=NewTestClass ();Echo $class;?>This method can only return a string, and cannot throw an exception in this method, or a fatal error will occur. __invoke () invokes a function in a way that invokes an object when the response method is called. as follows<?PHPclassCallableclass {function__invoke () {Echo' This is a object '; }}$obj=NewCallableclass;Var_dump(is_callable($obj));?>This static method is called when __set_state () calls Var_export () to export the class. <?PHPclassa{ Public $var 1;  Public $var 2;  Public Static function__set_state ($an _array) {        $obj=NewA; $obj-&GT;VAR1 =$an _array[' Var1 ']; $obj-&GT;VAR2 =$an _array[' Var2 ']; return $obj; }}$a=NewA;$a-&GT;VAR1 = 5;$a->var2 = ' foo ';Var_dump(Var_export($a));?>__clone () Called when the object copy is complete. For example, in the design pattern in detail and the implementation of PHP: Singleton mode in the article mentioned in the implementation of the Singleton mode, using this function to prevent the object from being cloned. <?PHP Public classSingleton {Private Static $_instance=NULL; //Private Construction Methods    Private function__construct () {} Public Static functiongetinstance () {if(Is_null(Self::$_instance) ) { self::$_instance=NewSingleton (); }        returnSelf::$_instance; }    //Preventing cloned Instances     Public function__clone () { die(' Clone is not allowed. ')E_user_error); }}?>Magic Constants (Magic constants) Most of the constants in PHP are immutable, but there are 8 constants that change with the location of their code, and these 8 constants are called Magic constants. __line__, the current line number in the file__file__, the full path and filename of the file __dir__, the directory where the file resides__function__, the function name__class__, the name of the class __trait__,trait__method__, the method name of the class __namespace__, the name of the current namespace these Magic constants are often used to obtain current environment information or log logs. 

Magic method in PHP (Magic methods) and solid magic

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.