Summary of the PHP magic Method (continuous update)

Source: Internet
Author: User

Magic methods in the class

The PHP Magic method refers to built-in functions that are automatically called at some point, starting with two consecutive underscores.

Magic method in Class __construct ()

Class constructor that initializes the object and runs automatically when the object is instantiated

__destruct ()

destructor, which frees the memory occupied by the object when the PHP run terminates . destructor is the garbage collection mechanism of PHP, using stack structure, LIFO.

Examples of constructors and destructors
Class computer{private $brand;    function __construct ($brand) {$this->brand = $brand; } function __destruct () {echo "release". $this->brand. "    <br> ";  }} $myComputer = new computer ("MAC"), $yourComputer = new computer ("Asus"), $hisComputer = new computer ("Dell"); echo "End of PHP file<br> ";

The output results are as follows

End of PHP filerelease dellrelease asusrelease MAC

You can see that the destructor is executed after the PHP file execution is finished.

__get ($name)

A member property or method defined with the protected and private keywords in a class cannot be accessed through an instance of an object. The __get () method will and will only be executed automatically when an instance of the object accesses proctected and private member properties (no access to the member method, because it is meaningless).

The meaning of the __get () method is that the proctected and private member properties are processed after the output.

__get () has and only one input parameter

An example of the __get () method
class computer{    private  $brand;    protected  $owner;     public  $price;     function __construct ($brand,  $ owner,  $price) {         $this->brand =  $brand;          $this->owner =  $owner;          $this->price =  $price;     }    function  __get ($name) {        echo  "It" S up to me  to decide if let you konw the owner and the brand  of this computer or not :) <br> ";         echo  "i will tell you the name of woner: ". $this Owner. " <br> ";        echo  "I won ' T tell you that the brand  is  ". MD5 ($this->brand)." <br> ";        echo " <br> "&NBSP;&NBSP;&NBSP;&NBSP;}     function __destruct () {        echo  " release  ". $this->brand." <br> ";     }} $myComputer  = new computer (" MAC ", " Me ", " 1000 ") , $yourComputer  = new computer ("Asus",  "You",  "), $hisComputer  = new  computer ("Dell",  "his",  "");echo  $myComputer->price; echo  "<br>< Br> ";echo  $myComputer->owner;echo  $yourComputer->brand;echo " end of php  file<br> ";

The output is as follows

1000It s up to me decide if let konw the owner and the brand of this computer or not:) I'll tell you the name of Woner:mei won ' t tell you which the brand is 2e25c285356cbb0ed8785a1377027d79it's up to me to decide if let's konw the OW NER and the brand of this computer or not:) I'll tell you the name of the Woner:youi won ' t-tell-you-the-the-brand is Cb6ab 3315634a1e4d11b091ba48b60baend of PHP filerelease dellrelease asusrelease MAC

You can see that when you access the public member property price, the __get () method is not called. When we output brand, we use MD5 to encrypt it, and the use of the output after processing the encapsulated member property is the meaning of the Get method.

__set ($name, $value)

__set ($name, $value) is used to re-assign or define a method or property that is encapsulated in the current class.

Similar to get but different, __set ($name, $value) is executed automatically when the member property is assigned to a value, where $name is the name of the member property being accessed, $value the value assigned to the member property

Example of __set ()
class computer{    private  $brand;    protected  $owner;     function __construct ($brand,  $owner,  $price) {          $this->brand =  $brand;         $ this->owner =  $owner;         $this->price =  $price;     }    function __get ($name) {         echo  "It ' s up to me to decide if let you  konw the owner and the brand of this computer or not  :) <br> ";        echo " i will tell you  the name of woner:  ". $this->owner." <br> ";         echo&nbSP; " I won ' t tell you that the brand is  '. MD5 ($this->brand). " <br> ";        echo " <br> "&NBSP;&NBSP;&NBSP;&NBSP;}     function __set ($name,  $value) {          $this->owner =  $value;        echo  "set $ name to  $value "." <br><br> ";     }    function __destruct () {         echo  "release ". $this->brand. " <br> ";     }} $myComputer  = new computer (" MAC ", " Me ", " 1000 ") ;echo  $myComputer->owner =  "my friend";echo  $myComputer->owner;echo  "End  of php file<br> ";

Output results

Set owner to my friendmy Friendit's up to me decide if let's konw the owner and the brand of this computer or not:) I Would tell you the name of Woner:my Friendi won ' t tell you the the brand is 2e25c285356cbb0ed8785a1377027d79end of Php F Ilerelease MAC

We see that the set is called when the owner is assigned a value, and get is called when the property is accessed.

__tostring ()

Used to print the object handle directly, that is, when we use the Echo Plus object name, __torsring () will be automatically called

__tosring () example
Class computer{function __tostring () {return "This is a computer class"; }} $myComputer = new computer (); Echo $myComputer;

If you do not have the __totring () method, we are unable to use the Echo+ object name and the fatal error will appear

__call ($method, $arguments)

When we call a method that does not exist, __call () is automatically executed for exception handling and The program continues to function properly .

__call () example
Class computer{function Start () {echo "Starting computer<br>";        } function __call ($m, $a) {echo "Erro function:". $m;        echo "<br>";        echo "error param:";        Print_r ($a);    echo "<br>"; }} $myComputer = new computer (); $myComputer->start (); $myComputer->shutdown (' Ten min ', ' min '); echo "Here";

The output result is

Starting Computererro function:shutdownerror Param:array ([0] = ten min [1] = min) here

We can see that the $method returned the wrong function name, and arguments returned the parameter, and finally output the "Here" instructions to continue to run normally.

__clone () method and clone keyword

The Clone keyword is used to copy the object, and the __clone () method automatically calls the function when the object is cloned

Clone example
Class computer{public $name;    function __clone () {echo "A computer has been cloned<br>"; }} $myComputer = new computer (); $youComputer = $myComputer; $youComputer->name = ' PC1 '; echo "My computer's name is". $myC Omputer->name. " <br> "; echo" <br> "; $hisComputer = Clone $myComputer; $hisComputer->name = ' PC2 '; echo" My computer ' s name is ". $myComputer->name." <br> "; echo" his computer's name is ". $hisComputer->name." <br> ";

Output results

My computer ' s name is PC1A computer have been clonedmy computer ' s name is pc1his computer ' s name is PC2

We see that with the = sign does not copy the object, just add an alias to the object, here $myComputer and $youComputer point to the same piece of memory, modify the value of the $youComputer equivalent to modify the value of the $myComputer.

__autolaod ()

When instantiating an object, __autolaod () is automatically called for quick access to the corresponding class file

__autoload () example
<?phpfunction __autoload ($class _name) {include $class _name. '. php ';} $obj = new MyClass1 (); $obj 2 = new MyClass2 ();?>

Excerpt from PHP manual

Example with try, catch exception handling

function __autoload ($class _name) {echo "Want to load". $class _name. "    <br> "; if (file_exists ($class _name.). Class.php ")) {include ($class _name.").    Class.php "); }else{throw new Exception ("Unable to laod". $class _name. ".    Class.php "); }}try{$obj = new MyClass ();} catch (Exception $e) {echo $e->getmessage (). " <br> ";}

This article from "playing a basketball is so difficult" blog, please be sure to keep this source http://gipanda.blog.51cto.com/3808693/1423752

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.