Introduction and use of PHP magic methods and Magic constants

Source: Internet
Author: User
Tags export class
Some things, if not used frequently, can easily be forgotten, such as magic methods and magic constants.

Magic Method (Magic methods)

PHP's method of starting with two underscores is called a magic method, which plays a pivotal role in PHP. Magic methods include:

__construct (), constructor of class

__destruct (), Destructor for class

__call (), called when an inaccessible method is called in an object

__callstatic (), called when a non-accessible method is called in a static manner

__get (), which is called when a member variable of a class is obtained

__set (), which is called when a member variable of a class is set

__isset (), called when isset () or empty () is called on an inaccessible property

__unset () is 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 (), which is a method of responding when a class is treated as a string

__invoke (), called when a function is called in a way that responds to an object

__set_state (), this static method is called when the Var_export () export class is called.

__clone (), called when the object copy is complete

__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);}    }? >

Magic constant (Magic constants)

The constants in PHP are mostly constant, but there are 8 constants that change as their code positions change, and these 8 constants are called Magic constants.

__line__, the current line number in the file

__file__, the full path and filename of the file

__dir__, the directory where the files are located

__function__, Function name

__class__, the name of the class

__trait__,trait's name.

__method__, method name of the class

__namespace__, the name of the current namespace

These Magic constants are often used to obtain current environmental information or log records.

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