Introduction and use of magic methods and magic constants in PHP

Source: Internet
Author: User
Some things, if not often used, are easy to forget, such as magic methods and magic constants. Magicmethods (Magicmethods) PHP calls the methods starting with two underscores _ as magic methods, which play an important role in PHP. Magic methods include __construct (), Class constructor _ destruct (), and class destructor

Some things, if not often used, are easy to forget, such as magic methods and magic constants. Magic methods (Magic methods) PHP calls the methods starting with two underscores _ as Magic methods, which play an important role in PHP. Magic methods include: _ construct (), Class constructor _ destruct (), Class Structure

Some things, if not often used, are easy to forget, such as magic methods and magic constants.

Magic method (Magic methods)

In PHP, underline__The methods at the beginning are called magic methods, which play an important role in PHP. Magic methods include:

  • __construct(), Class Constructor
  • __destruct(), Class destructor
  • __call()To call an inaccessible method in an object.
  • __callStatic()To call an inaccessible method in static mode.
  • __get()To obtain the member variables of a class.
  • __set(), Called when setting a class member variable
  • __isset()When you call an inaccessible attributeisset()Orempty()Time call
  • __unset()When you call an inaccessible attributeunset()Is called.
  • __sleep(), Executeserialize()This function is called first.
  • __wakeup(), Executeunserialize()This function is called first.
  • __toString()Response method when the class is treated as a string
  • __invoke()The method of calling a function to call the response method of an object.
  • __set_state(), Callvar_export()When exporting a class, this static method is called.
  • __clone()Called when the object copy is complete.
__construct()And __destruct()

Constructor and destructor should not be unfamiliar. They are called when the object is created or eliminated. For example, we need to open a file, which is opened when the object is created, and closed when the object is killed.


  handle = fopen(...);    }    function __destruct(){        fclose($this->handle);    }}?>

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


  
__call()And __callStatic()

When an inaccessible method is called in an object, the two methods are called, and the latter is a static method. These two methods may be used in Variable functions calls.


  runTest('in object context');MethodTest::runTest('in static context');?>
__get(), __set(), __isset()And __unset()

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


  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 are executingserialize()Andunserialize()The 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. Example:


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

Response method when the object is treated as a string. For exampleecho $obj;To output an 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. As follows:


  
__set_state()

Callvar_export()When exporting a class, this static method is called.


  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, detailed description of the design mode and PHP implementation: This function is used to prevent the object from being cloned.


  
Magic constants)

Most constants in PHP remain unchanged, but eight constants change with the change of their code location. These eight constants are called magic constants.

  • __LINE__, The current row number in the file
  • __FILE__, Complete file path and file name
  • __DIR__, Directory of the file
  • __FUNCTION__, Function name
  • __CLASS__, Class Name
  • __TRAIT__, Trait name
  • __METHOD__, Class method name
  • __NAMESPACE__, Name of the current namespace

These magic constants are often used to obtain information about the current environment or record logs.

Original article address: introduction and use of magic methods and magic constants in PHP. Thank you for sharing it with the original author.

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.