Examples of magic methods in PHP

Source: Internet
Author: User
Tags export class
What is a magic method?

In the PHP object-oriented, provides a series of magic methods, these magic methods for our programming provides a lot of convenience, PHP in the beginning of the two underscore __ method is called Magic method, these magic methods do not need to display the call but a certain conditions to start. This chapter will give you a quick look at the magic methods available in PHP.

The Magic method of PHP is the following table:

Function Description
__construct () Constructors for classes
__destruct () Destructors for classes
__call () Called when an inaccessible method is called in an object
__callstatic () Called when a non-accessible method is called in a static way
__get () Called when a member variable of a class is obtained
__set () Called when a member variable of a class is set
__isset () Called when isset () or empty () is called on an inaccessible property
__unset () Called when unset () is called on a non-accessible property.
__sleep () When executing serialize (), this function is called first
__wakeup () When executing unserialize (), this function is called first
__tostring () A method of responding when a class is treated as a string
__invoke () Method of responding when calling an object in a way called a function
__set_state () This static method is called when the Var_export () export class is called.
__clone () Called when the object copy is complete

"__" in the table above is two underline, not a "_"

Let's take a look at some examples of these magic methods

__construct () and __destruct ()

Constructors and destructors should be unfamiliar, and 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

<?phpclass fileread{    protected $handle = NULL;    function __construct () {        $this->handle = fopen (...);    }    function __destruct () {        fclose ($this->handle);    }}? >

These two methods can be extended during inheritance, for example:

<?phpclass Tmpfileread extends fileread{    function __construct () {        parent::__construct ();    }    function __destruct () {        parent::__destruct ();    }}? >

__call () and __callstatic ()

These two methods are called when an inaccessible method is called in an object, which is a static method. These two methods may be used in the variable method (Variable functions) call.

<?phpclass methodtest{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 = new Methodtest; $obj->runtest (' in object context '); Methodtest::runtest (' in static context ');? >

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

These two functions are called when get/set a member variable of a class. For example, we save an object variable in another array, not the member variable of the object itself.

<?phpclass methodtest{    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:

<?phpclass 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 ()

The method that the object responds to as a string. For example, use echo $obj to output an object

<?php//Declare A simple classclass testclass{public    function __tostring () {        return ' This is a object ';    } } $class = new TestClass (); Echo $class;? >

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. As follows

<?phpclass callableclass{    function __invoke () {        echo ' This is a object ';    }} $obj = new Callableclass;var_dump (is_callable ($obj));? >

__set_state ()

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

<?phpclass 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 '; 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.

<?phppublic class Singleton {    private static $_instance = NULL;    Private constructor Method     __construct () {} public    static function getinstance () {        if (Is_null (self::$_ Instance) {            self::$_instance = new Singleton ();        }        return self::$_instance;    }    Prevents the clone instance public    function __clone () {die        (' clone was not allowed. '). E_user_error);}    }? >

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.