Magic methods in php

Source: Internet
Author: User
: This article mainly introduces the magic methods in php. if you are interested in the PHP Tutorial, you can refer to them. PHP magic method:

_ Construct (), _ destruct (), _ call (), _ callStatic (), _ get (), _ set (), _ isset (), _ unset (), _ sleep (), _ wakeup (), _ toString (), _ invoke (), _ set_state (), _ clone (), and _ debugInfo () are called "Magic methods" (Magic methods) in PHP ). You cannot use these method names when naming your own class methods unless you want to use their magic functions.

_ Construct (), constructor _ destruct () of the class, destructor _ call () of the class, and an inaccessible method called in the object (private or non-existent) call _ callStatic (), call _ get () when calling an inaccessible method in static mode, and call _ set () when obtaining a member variable of a class (), _ isset () is called when a class member variable is set. _ unset () is called when isset () or empty () is called for an inaccessible attribute (), this API is called when unset () is called for an inaccessible attribute. _ Sleep (): When serialize () is executed, the _ wakeup () function is called first. when unserialize () is executed, the _ toString () function is called first (), response Method _ invoke () when the class is treated as a string, response method _ set_state () when a function is called, and response method _ set_state () when var_export () is called to export the class, this static method is called. _ Clone (), called when the object copy is complete

_ Construct () and _ destruct ()
Construct _ construct () is called when an object is created. destructor _ destruct () is called when the object is extinct.

 ';} Function _ destruct () {echo' in the destructor
';}}$ Val = new ConDes (); unset ($ val) ;?>
Output:

In the destructor

When _ call () and _ callStatic () call an inaccessible method in an object, these two methods are called. The latter is a static method.

  ";    }    public static function __callStatic ($name, $arguments) {        echo "static method $name and ".implode(',',$arguments)."
";    }}$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 obtain an inaccessible class member variable or 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 'AAA' (length = 4)
_ Get
Array (size = 1)
'A' => string 'AAA' (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, this object has a database link. to restore the link status in deserialization, we can reconstruct these two functions to restore the link.

  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_query($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 ()
Response method when the object is treated as a string. For example, echo $ obj;

  
Output:

This is a object

This method can only return a string and cannot throw an exception in this method. Otherwise, a fatal error occurs.

_ Invoke ()
The response method when a function is called.

  ';}}class noInvoke{}$obj = new Invoke();$obj();var_dump(is_callable($obj));$obj2 = new noInvoke();//$obj2();var_dump(is_callable($obj2));

Output:

In invoke
Boolean true
Boolean false

_ Set_state ()
This static method is called when var_export () is called to export the class.

  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 constant: introduction here

The above describes the magic methods in php, including some content, and hope to help those who are interested in PHP tutorials.

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.