How to use the PHP Magic Method (Magic methods), magicmethods_php tutorial

Source: Internet
Author: User
Tags export class

Explain how the PHP Magic Method (Magic methods) is used, magicmethods


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

<?php class fileread{Protected $handle = NULL, function __construct () {  $this->handle = fopen (...)} function __destruct () {  fclose ($this->handle);}}? >

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

<?php class 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"; The 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.

<?php class methodtest{Private $data = Array (), Public function __set ($name, $value) {  $this->data[$name] = $val Ue The 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 ($serve R, $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); The Public Function __sleep () {  return array (' Server ', ' username ', ' password ', ' db '), and 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.

<?php public class Singleton {private static $_instance = NULL;//Private constructor Method private  function __construct () {} public static function getinstance () {  if (Is_null (self::$_instance)) {   self::$_instance = new Singleton ();  }  return self::$_instance; }//Prevent 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.

The above is the whole content of this article, I hope that everyone's study has helped.

Articles you may be interested in:

    • Instructions for using the PHP magic method
    • Explanation of PHP's Magic Methods __get () and __set () usage Introduction
    • In-depth analysis of the PHP magic method and Magic variables, built-in methods and built-in variables
    • Based on the PHP5 Magic constants and the magic method of the explanation
    • PHP Tutorial Magic Method Use Example (PHP magic function)
    • A brief description of magic method in thinkphp query
    • A concise summary of the Magic method in the PHP class
    • PHP 5.3 New Magic Method __invoke Overview

http://www.bkjia.com/PHPjc/1099055.html www.bkjia.com true http://www.bkjia.com/PHPjc/1099055.html techarticle explain the use of the PHP Magic Method (Magic Methods) method, Magicmethods PHP to the beginning of the two underscore the method called Magic method, these methods in PHP play a pivotal role in ...

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