Introduction and use of magic methods and magic constants in PHP

Source: Internet
Author: User
Tags export class

Magic Method (Magic methods)

PHP, which starts with two underscores __ , is called the Magic Method, which plays a pivotal role in PHP. Magic methods include:

  • __construct(), the constructor for the class
  • __destruct(), a destructor for a 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()is called when a member variable of a class is obtained.
  • __set()That is called when a member variable of a class is set.
  • __isset()Called when an unreachable property is invoked isset() or empty()
  • __unset()Called when a call to an inaccessible property is called unset() .
  • __sleep(), serialize() This function is called first when executed.
  • __wakeup(), unserialize() This function is called first when executed.
  • __toString(), the class is treated as a string response method
  • __invoke()A method of responding when invoking an object in a way that invokes a function
  • __set_state(), var_export() This static method is called when the 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 = nullfunction __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.

<?phpClassMethodtest{Publicfunction__call($name,$arguments){Echo"Calling object Method"$name‘ ".Implode(‘, ‘,$arguments)."\ n";}PublicStaticfunction__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.

<?phpClassMethodtest{Private$data=Array();Publicfunction__set($name,$value){$this-Data[$name]=$value;}Publicfunction__get($name){If(Array_key_exists($name,$this-Data))Return$this-Data[$name];Returnnull} 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() , we call these two functions 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:

<?phpClassConnection{Protected$link;Private$server,$username,$password,$db;Publicfunction__construct($server,$username,$password,$db){$this-Server=$server;$this-Username=$username;$this-Password=$password;$this-Db=$db;$this-Connect();}PrivatefunctionConnect(){$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 () Span class= "P" >{ $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()

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

<?phpClassA{Public$var 1;Public$var 2;PublicStaticfunction__set_state($an _array){$obj=NewA;$obj-Var1=$an _array[' Var1 ']; $obj ->var2 =  $an _array< Span class= "p" >[ ' var2 ' ; return  $obj }} $a = new A< Span class= "P";  $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.

<?phpPublicClassSingleton{PrivateStatic$_instance=Null;Private construction methodsPrivatefunction__construct(){}PublicStaticfunctionGetInstance(){If(Is_null (self::$_instance{self::$_instance = new singleton (); } return self::$_instance} //Prevent clone instance public function __ Clone () {die ( ' Clone is 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__, the function name
    • __CLASS__, the name of the class
    • __TRAIT__, Trait's name
    • __METHOD__, the 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.

Introduction and use of magic methods and magic constants in PHP

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.