The Magic method in object-oriented oop in PHP

Source: Internet
Author: User

One, what is the Magic method:

PHP provides us with a series of functions that begin with __, which do not need to be called manually, and are called automatically at the right time, such functions as magic functions.
For example:

function __construct () {} is  called automatically when new object is newly

In PHP, there are magic methods and their effects:
1.__construct (): constructor, automatically called when new object

eg

class person{        public$name;          Public $age ;                 function __construct ($name,$age) {            $this->name= $name ;             $this->age=$age;        }}

The __construct () function is automatically called when new Person object is newly, assigning the passed arguments to the $name,$age.


2.__destruct (): destructor, called automatically before an object is destroyed

class person{        public$name;          Public $age ;                function __destruct () {        echo "This object was destroyed";    }}

As mentioned above, this magic method is executed when the object is destroyed


3.__get (): automatically called when accessing private properties in a class, passing read property names, returning $this-> property names

class person{        private$name;          Public $age ;                 function __get ($name) {          return$this,$name ;        }}

As in the code, the $name is set as a private property and cannot be read directly by $this->name;, so the __get () Magic method needs to be set to read.


4.__set (): Automatically called when assigning a value to a private property of a class, passing property names to be set, property values

class person{        private$name;          Public $age ;                 function __set ($key,$value) {            $this-$key =$value;        }}

With the __get () method, the private property cannot be set directly by $this->name= "AAA", the __set () method needs to be set, and the parameters passed in are the property name and the attribute value, respectively.


5.__isset (): Called when detecting private properties of an object using Isset, passing the detected property name, returning Isset ($this property name)

class person{        private$name;          Public $age ;                 function __isset ($name) {        returnisset($this $name);}    }

called when using Isset to detect the private properties of an object, as in the other.


6.__unset (): Called when the object private property is deleted using the unset () function, passing the deleted property name, executing the unset ($this-property name) in the method

Class person{        $name;         $agefunction __unset ($name) {
Unset ($this, $name);
}}

Ditto, called when a private property is removed with the unset () function.


7.__tostring (): Called When using echo to print an object, returns the content to be displayed when the object is printed, and returns a string

classperson{ Public $name;  Public $age; function__tostring () {$str= <<<str What you want to print is:<br>            \$name=>{$this->name};<br>            \$age=>{$this->age};<br>str; return $str; }}

called when you print an object with Echo, and returns what you want to display when you print the object .


8.__call (): called automatically when calling a method that is not defined or exposed in a class, passing the called function name and argument list

classperson{ Public $name;  Public $age; function__call ($funcName,$funcParams){            Echo"The function you are calling {$funcName}, the parameter list "; Print_r($funcParams); Echo"Does not exist/is not public"; }}
$zhangsan =new person ();
$zhangsan->say (a);

As shown in the code, the call does not exist for say (.

You call the function of the method, the parameter list array ([0] = 123) does not exist


9.__clone (): When cloning an object using the Clone keyword, it is called automatically to initialize the value of the newly cloned object

 class   person{ public   $name  ;  public   $age                ;  function   __clone () {  $this ->name=" Lisi "  $zhangsan  =new  person ("Zhangsan ", 24  $lisi  =clone   $zhangsan   echo   $lisi ->name; 

The printed result is "Lisi", not "Zhangsan".

10.__sleep (): Automatically called when the object is serialized, returns an array where the values in the array are the properties that can be serialized

class person{        public$name;          Public $age ;               function __sleep () {        returnarray("name", "Age");}    }

As in the above code, only "name" is used when serializing an object with serialize (), and the "age" property is serialized.


11.__wakeup (): Automatic invocation of object deserialization, initialization assignment for deserialization of newly generated objects

class person{        public$name;          Public $age ;               function __wakeup () {        $this , name = "Lisi";    }}

Serializes the object and then deserializes it, assigning an initial value of "Lisi" to the object's Name property.


12.__autolode (): You need to declare a function outside of the class, call it automatically when instantiating an undeclared class, pass the instantiated class name , you can use the class name to automatically load the corresponding class file.

function __autoload ($className) {    include ' class/'.  Strtolower($className). ". Class.php ";}     $zhangsan=new person (); $zhangsan->say ();

As the above code, the person class does not exist when calling the __autolode () method, loading a class written outside the file, "class/". strtolower ($className). ". class.php "; is the relative path to the class file,$className is

The class name of the class that is not in this file, so the naming method must be a lowercase class name when creating an external class file. class.php. The __autolode () method is also the only one by one magic methods that are not written in the class.

The above is the Magic method in PHP, reasonable use of these methods can easily achieve the various operations of the object.

Magic methods in object-oriented oop in PHP

Related Article

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.