PHP Magic Method

Source: Internet
Author: User

__construct (), __DESTURCT (), __call (), __callstatic (), __get (), __set (), __isset (), __unset (), __sleep (), __wakeup (), __ ToString (), __invoke (), __set_state (), __clone (), and, __debuginfo () are known in PHP as " Magic Methods" (Magic methods). You cannot use these method names when naming your own class methods.

Note: __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,unserlalize () 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:Sleep and Wakeup

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

PHP Magic Method

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.