PHP Magic Method

Source: Internet
Author: User
Tags export class
__construct (), __destruct (), __call (), __callstatic (), __get (), __set (), __isset (), __unset (), __sleep (), __wakeup (), __ ToString (), __invoke (), __set_state (), and __clone () are called "Magic methods" in PHP. You cannot use these method names when naming your own class methods, unless you want to use their magic features.

PHP retains all class methods that begin with __ (two underscores) as a magic method. Therefore, in addition to the above magic method when defining a class method, it is recommended that you do not prefix __.

__sleep () and __wakeup ()

Publicarray__sleep (void)

Void__wakeup (void)

The serialize () function checks to see if there is a magic method __sleep () in the class. If present, the method is called first before the serialization operation is performed. This feature can be used to clean up an object and return an array containing all the variable names that should be serialized in the object. If the method does not return anything, NULL is serialized and a E_notice level error is generated.

Attention:

__sleep () cannot return the name of the private member of the parent class. Doing so produces a e_notice level of error. Can be replaced with Serializable interface.

The __sleep () method is commonly used to commit uncommitted data, or similar cleanup operations. At the same time, if there are some very large objects, but do not need to save all, this function is very useful.

In contrast, unserialize () checks for the existence of a __wakeup () method. If present, the __wakeup method is called before the resource required by the object is prepared beforehand.

__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. e.g. Echo $obj; What should be shown. This method must return a string, otherwise a fatal error of E_RECOVERABLE_ERROR level will be emitted.

You cannot throw an exception in the __tostring () method, which results in 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

It should be noted that before PHP 5.2.0, the __tostring () method only takes effect when used directly with Echo or print. After PHP 5.2.0, you can take effect in any string environment (for example, with the%s modifier through printf (), but not in a non-string environment (such as using the%d modifier). From PHP 5.2.0, if an object that does not define the __tostring () method is converted to a string, a E_recoverable_error level error is generated.

__invoke ()

Mixed__invoke ([$ ...])

The __invoke () method is called automatically when an attempt is made to invoke an object in a way that invokes a function.

Attention:

This feature is only available in PHP 5.3.0 and above.

Example #3 using __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 This static method is called when the Var_export () export class is called.

The only argument to this method is an array that contains the class properties arranged in the format of the array (' property ' = = value, ...).

Example #4 using __set_state () > (from PHP 5.1.0)

Class a{public    $var 1;    Public $var 2;    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.