The Magic method commonly used in PHP

Source: Internet
Author: User

PHP Object-oriented has a lot of features are very powerful, have to say is the Magic method. Take time today to record some of the more common magic methods:

1.__construct This is a constructor, a function that is called automatically when a class is instantiated. Then we can initialize the value of the variable here. For example:

classscore{ Public $chinese;  Public $english;  Public $math;  Public function__construct ($chinese=100,$english=99,$math=98)    {        $this->chinese=$chinese; $this->english=$english; $this->math=$math; }     Public functionShow () {Echo"chinese:{$this->chinese},english:{$this->english},math:{$this->math} "; }

At this point, we can instantiate a score object, and then call the score class's Show method, for example:

$stu New score (); $stu->show ();

We instantiate an object that has no value, and this time it prints out

Chinese:100,english:99,math:98

2.__destruct the destructor. As the name implies, his function is antagonistic to the constructor, and when the object is destroyed, the destructor runs, or it is clear that PHP will clean it up for us when we no longer use it.

 Public  function __destruct ()    {        echo "I was destroyed {$this->math}";
}

3.__set () assigns a value to a property, and then uses another Magic Method __get () to take a value

classuser{Private $name; Private $age; /*****__set (): Assignment * * **/    function__set ($name,$value)    {        if($name= = "Age"){            if($value<18){                $this->age = 18; }Else{                $this->age =$value; }        }Else{            $this-$name=$value; }    }}

4.__get (); When the __set () method assigns values to certain properties, it is possible to use __get () to take any property after the assignment, as follows:

classuser{Private $name; Private $age; /****__get (): Take value * **/    function__get ($name)    {        if($name= = "Name"){            return"Dog"; }Else{            return $this-$name; }    }}

5.__isset (); Determine if it is this attribute 当当前属性被isset()或者empty(),即当某个属性被检验空的方法调用的时候,会触发这个方法 ;

class user{    private$name;     Private $age ;      Public function __isset ($name)    {        echo ' {$name} Isset was called ";    }}

The calling method is as follows:

$user New User (); $user->name = "Fusaaki"; isset ($user

6.__unset (); destroy this attribute;

class user{    private$name;     Private $age ;       function __unset ($name)    {        echo "{$name} was destroyed" ;         // to prevent the destruction of the time directly write a return can be;     }}

The calling method is as follows:

$user New User (); $user->name = "Fusaaki"; unset ($user->name);

7.__clone():克隆的时候会调用__clone方法;

classfour{ Public $name;  Public $age;  Public function__construct ($name,$age)    {        $this->name =$name; $this->age =$age; }     //the __clone method is called when cloning     Public function__clone () {$this->age = 0; }    }

The calling method is as follows:

$four New Four ("ZHQ"); $four 2 Clone $four // at this point the $FOUR2 call is the __clone method, so the age will change to 0

8.__call:当类里面没有方法的时候会调用__call方法;

classfour{ Public $name;  Public $age;  Public function__construct ($name,$age)    {        $this->name =$name; $this->age =$age; }     //the __call method is called when there are no methods in the class.    function__call ($name,$arguments)    {        EchoNo$name} This method, can't play this Way "; }    }

The calling method is as follows:

$four New Four ("ZHQ"); $four ->show (); // class does not have this method, the __call method is called

9.__tostring ();当echo的时候会调用__toString方法;

classfour{ Public $name;  Public $age;  Public function__construct ($name,$age)    {        $this->name =$name; $this->age =$age; }    //当echo的时候会调用__toString方法;      $stu= "chinese:{$this->chinese},english:{$this->english},math:{$this->math} "; return $stu; }

The calling method is as follows:

New Four ("ZHQ");  $four; when Echo is instantiated, the ToString method is called directly  

10.__autoload:自动加载,当类路径找不到的时候会调用__autoload方法,这个方法很好的解决了需要引用多个include_once的问题;

classfour{ Public $name;  Public $age;  Public function__construct ($name,$age)    {        $this->name =$name; $this->age =$age; }    //the __tostring method is called when Echo is used;      $stu= "chinese:{$this->chinese},english:{$this->english},math:{$this->math} "; return $stu; }

If you call the four class on another page;include_once Four;为了避免代码重复,则有以下方法

function __autoload ($name) {    $path$name. ". Class.php ";     include_once $path ;} There is no need to  introduce four classes at this time, so you can instantiate an object directly

11.__sleep (): Call this function when the object is serialized

classfour{ Public $name;  Public $age;  Public function__construct ($name,$age)    {        $this->name =$name; $this->age =$age; }    //when the object is serialized, the moment    function__sleep () {//todo:implement __sleep () method.        Echo"I'm going to sleep <br>"; return Array(' name ', ' age '); }}

This time we can serialize the object, we call the __sleep () method;

$four New Four ("ZHQ");
Serialize the object $four 1=Serialize($four);
Writes the file to the string file_put_contents("Score.txt",$four 1);

12.__wakeup (): This function is called when the object is crossdress.

classfour{ Public $name;  Public $age;  Public function__construct ($name,$age)    {        $this->name =$name; $this->age =$age; }     //when the object is crossdress, that moment.     Public function__wakeup () {Echo"I'm Back Again <br>"; //todo:implement __wakeup () method.    }  }

The __wakeup () method is called when we can crossdress the object at this time;

// Read File $four file_get_contents ("Score.txt"); $obj unserialize ($four);

At present, the first record of these basic magic methods, do not know if there is no error, I hope that everyone to correct, open-minded learning, accumulate knowledge! Thank you, I will add other magic methods later.

The Magic method commonly used 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.