Php magic method

Source: Internet
Author: User
_ Construct () ,__ destruct () ,__ call () ,__ callStatic () ,__ get () ,__ set () ,__ isset (), __unset () ,__ sleep () ,__ wakeup () ,__ toString () ,__ invoke () ,__ set_state () and _ construct (), __destruct () ,__ call () ,__ callStatic () ,__ get () ,__ set () ,__ isset () ,__ unset () ,__ sleep (), __wakeup () ,__ toString () ,__ invoke () ,__ set_state () and _ clone () and other methods 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.

PHP retains all class methods starting with _ (two underscores) as magic methods. Therefore, we recommend that you do not use the _ prefix in addition to the above magic methods when defining class methods.

_ Sleep () and _ wakeup ()

Publicarray _ sleep (void)

Void _ wakeup (void)

The serialize () function checks whether a magic method _ sleep () exists in the class (). If this method exists, it is called first before the serialization operation is executed. This function can be used to clear an object and return an array containing all variable names in the object to be serialized. If this method does not return any content, NULL is serialized and an E_NOTICE-level error is generated.

Note:

_ Sleep () cannot return the name of the private member of the parent class. In this case, an error at the E_NOTICE level is generated. You can use the Serializable interface instead.

The _ sleep () method is often used to submit uncommitted data or similar cleanup operations. At the same time, if there are some large objects, but you do not need to save them all, this function is very useful.

In contrast, unserialize () checks whether a _ wakeup () method exists. If yes, the _ wakeup method is called first to prepare the resources required by the object.

_ Wakeup () is often used in deserialization operations, such as re-establishing a database connection or performing other initialization operations.

Example #1 Sleep and wakeup

class Connection{    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 function connect(){        $this -> link = mysql_connect($this->server,$this->username,$this->password);        mysql_select_db($this->db,$this->link);    }    public function __sleep(){        return array('server','username','password','db');    }    public function __wakeup(){        $this->connect();    }}

_ ToString ()

Public string _ toString (void)

The _ toString () method is used to respond to a class when it is treated as a string. For example, echo $ obj; what should be displayed. This method must return a string; otherwise, a fatal error at the E_RECOVERABLE_ERROR level will be issued.

You cannot throw an exception in the _ toString () method. doing so will cause a fatal error.

Example #2 Simple Example

class TestClass{    public $foo;    public function __construct($foo)    {        $this->foo = $foo;    }    public function __toString(){        return $this->foo;    }}$class = new TestClass('Hello');echo $class;

Output result:

Hello

Note that before PHP 5.2.0, the __tostring () method takes effect only when it is directly used for echo or print. PHP 5.2.0 and later can take effect in any string environment (for example, using the % s modifier through printf (), but cannot be used in non-string environment (for example, using the % d modifier ). From PHP 5.2.0, if an object of the undefined _ toString () method is converted to a string, an error of the E_RECOVERABLE_ERROR level will be generated.

_ Invoke ()

Mixed _ invoke ([$...])

When you try to call an object by calling a function, the __invoke () method is automatically called.

Note:

This feature is only available in PHP 5.3.0 and later versions.

Example #3 use _ invoke ()

class CallableClass{    function __invoke($x){        var_dump($x);    }}$obj = new CallableClass;$obj(5);var_dump(is_callable($obj));

Output result:

Int (5)

Bool (true)

_ Set_state ()

Static object _ set_state (array $ properties)

Since PHP 5.1.0, when var_export () is called to export a class, this static method is called.

The unique parameter of this method is an array, which contains class attributes in array ('properties' => value,...) format.

Example #4 use _ set_state ()> (from PHP 5.1.0)

class A{    public $var1;    public $var2;    public static function __set_state($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';eval('$b='.var_export($a,true).';');var_dump($b);

Output result:

Object (A) #2 (2) {["var1"] => int (5) ["var2"] => string (3) "foo "}

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.