The Illusion method in PHP

Source: Internet
Author: User
Tags export class
The Magic method in PHP

PHP Magic Method:

__construct (), __destruct (), __call (), __callstatic (), __get (), __set (), __isset (), __unset (), __sleep (), __wakeup (), __ ToString (), __invoke (), __set_state (), __clone (), and __debuginfo () are known in PHP as "Magic Methods" (Magic methods). You cannot use these method names when naming your own class methods, unless you want to use their magic features.


__construct (), the class's constructor __destruct (), the class's destructor __call (), calls an inaccessible method in the object (private or nonexistent) when called __callstatic (), invokes a non-accessible method in a static manner when called __ Get (), which 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 called unset () on an inaccessible property. __sleep (), when executing serialize (), first calls this function __wakeup (), executes Unserialize (), first calls the function __tostring (), the class is treated as a string when the response method __invoke (), This static method is called when the function is called when an object is called by the Response Method __set_state (), when the Var_export () export class is called. __clone (), called when the object copy is complete

__construct () and __destruct ()
The constructor __construct () is called when the object is created, and the destructor __destruct () is called when the object dies

 '; The function __destruct () {echo ' is in the destructor
'; }} $val = new ConDes (); unset ($val);? >

Output:

In a constructor, in a destructor

Both methods are called when __call () and __callstatic () call an inaccessible method in an object, which is a static method.

 
   "; The public static function __callstatic ($name, $arguments) {echo "static method $name and". Implode (', ', $argumen TS). "
"; }} $obj = new Methodtest; $obj->runtest (' In object context ', ' another Arg ');  Methodtest::runtest (' in static context '); ?>
Output:

Array (size=2)
0 = String ' In object context ' (LENGTH=17)
1 = String ' Another arg ' (length=11)

Object method Runtest and in Object Context,another arg
static method Runtest and in static context


__get (), __set (), __isset () and __unset ()

These two functions are called when you get an inaccessible class member variable or when you set an inaccessible class member variable.

 
   data[$name] = $value; Echo ' __set '; Var_dump ($this->data);    }    Public Function __get ($name) {echo ' __get '; Var_dump ($this->data);        if (Array_key_exists ($name, $this->data))            return $this->data[$name];        return NULL;    }    Public Function __isset ($name) {echo ' __isset ';        return Isset ($this->data[$name]);    }    Public Function __unset ($name) {echo ' __unset ';        unset ($this->data[$name]);}    } $in = new Methodtest (), $in->a = ' aaaa '; $aaa = $in->a; $res = isset ($in->c)? ' Set ': ' Not set '; Echo '
'. $res. '
'; unset ($in->a);? >
Output:

__set
Array (size=1)
' A ' = = String ' aaaa ' (length=4)
__get
Array (size=1)
' A ' = = String ' aaaa ' (length=4)
__isset
Not set
__unset


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

  Server = $server;        $this->username = $username;        $this->password = $password;        $this->db = $db;    $this->connect (); } Private Function Connect () {$this->link = mysql_connect ($this->server, $this->username, $this        ->password);    mysql_select_db ($this->db, $this->link); } public Function __sleep () {echo ' Sleep
';    Return array (' Server ', ' username ', ' password ', ' db '); } public Function __wakeup () {echo ' Wakeup
';    $this->connect (); }} $a = new Connection (' localhost ', ' mosi ', ' Moshi ', ' Test '); $sql = ' Select id,username from user Limit 1 '; $res = mysql_query ( $sql, $a->link); $res = Mysql_fetch_array ($res); Var_dump ($res); $sres = serialize ($a); Mysql_close ($a->link);// unset ($a); $unsres = Unserialize ($sres); Var_dump ($unsres); $sql = ' Select id,username from user Limit 1 '; $ress = Mysql_quer Y ($sql, $unsres->link); $ress = Mysql_fetch_array ($ress); Var_dump ($ress);? >
Output:

array (size=4)
0 => string '1' (length=1)
'id' => string '1' (length=1)
1 => string 'm0sh1' (length=5)
'username' => string 'm0sh1' (length=5)
sleep
wakeup
object(Connection)[2]
public 'link' => resource(6, mysql link)
private 'server' => string 'localhost' (length=9)
private 'username' => string 'moshi' (length=4)
private 'password' => string 'moshi' (length=5)
private 'db' => string 'test' (length=4)
array (size=4)
0 => string '1' (length=1)
'id' => string '1' (length=1)
1 => string 'm0sh1' (length=5)
'username' => string 'm0sh1' (length=5)


__toString()

对象当成字符串时的回应方法。例如使用echo $obj;

 
   
Output:

This is a object

This method can only return a string, and cannot throw an exception in this method, or a fatal error will occur.


__invoke ()

A method of responding when invoking an object in a way called a function.

 
   ';}} Class noinvoke{} $obj = new Invoke (), $obj (), Var_dump (Is_callable ($obj)), $obj 2 = new Noinvoke ();//$obj 2 (); Var_dump (Is_ Callable ($obj 2));

Output:

In Invoke
Boolean true
Boolean false


__set_state ()

This static method is called when the Var_export () export class is called.

 
   var1 = ' Var11 ';        $obj->var2 = $arr [' var2 '];        return $obj;    }} $a = new A; $a->var1 = 5; $a->var2 = ' foo '; var_dump ($a);  Var_export ($a);  Eval (' $ress = '. Var_export ($a, true). '; '); Var_dump ($ress);? >

Output:

Object (A) [1]
Public ' var1 ' + int 5
Public ' var2 ' = String ' foo ' (length=3)
A::__set_state (Array (' var1 ' = 5, ' var2 ' = ' foo ',))
Object (A) [2]
Public ' var1 ' = String ' Var11 ' (length=5)
Public ' var2 ' = String ' foo ' (length=3)


__clone ()

Called when the object copy is complete.

 
   ';} $c = Clone $b;? >

Output:

Equal
Clone is not allowed error:256


PHP Magic constants: Introduction here

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