PHP Learning (ii):P HP's Magic Method

Source: Internet
Author: User
Tags call back
PHP treats all class methods that begin with __ (two underscores) as a magic method. So when you define your own class method, do not prefix __.

1, __construct ()

When an object is instantiated, the method of constructing the object is called first;

We know that the PHP5 object model and the same class name function are the constructors of the class, so if you define both the constructor and the __construc () method, PHP5 will call __contruct () by default without calling the same name function, so __contruct () As the default constructor for a class;

Header (' Content-type:text/html;charset=utf-8 ');      Class person{    private $name;    /**     * constructor-called when you call new person to create an object.     * @param string     *    /function __construct ($name = ' La ') {        echo ' call construct '. $name;    }} $obj = new Person ();//Will output "call construct" five words

2, __destruct ()

Destructors are removed when all references to an object are deleted or executed when an object is explicitly destroyed.

Header (' Content-type:text/html;charset=utf-8 ');      Class person{    private $_name;    function __construct ($val) {        $this->_name = $val;    }        function __destruct () {        echo $this->_name. ' Call destructor
'; } } $obj 1 = new Person (' 1 '), $obj 2 = new Person (' 2 '), $obj 3 = new Person (' 3 '), or//because memory is stored in a heap, the principle of destruction is LIFO, so Obj3 is first destroyed, output the following// 3 Call destructor//2 call destructor//1 call destructor

Header (' Content-type:text/html;charset=utf-8 ');      Class person{    private $_name;    function __construct ($val) {        $this->_name = $val;    }        function __destruct () {        echo $this->_name. ' Call destructor
'; } } $obj 1 = new Person (' 1 '), $obj 2 = new Person (' 2 '); unset ($obj 2); $obj 3 = new Person (' 3 ');//Noteworthy, If you remove the obj2 in the middle with unset or remove the output with the Obj2=null display the following//will perform the destruction obj2 and then execute the OBJ3//2 call destructor//3 call destructor//1 call destructor

3, __get (string $name)

Called when an attempt is made to read a property that does not exist, and PHP gives incorrect information when attempting to read a property that does not exist on an object. If you add the __get method to the class, and we can use this function to implement a variety of actions like reflection in Java.

Header (' Content-type:text/html;charset=utf-8 ');      Class person{    private $name;    function __get ($val) {        return ' does not have a property of this name '. $val;    }} $obj = new Person (); Echo $obj->name;//Call the value of the property when the property is not called, the __get () Magic function can be called  $val that is, you call the property name//The notable thing is that there is no private modifier defined, All belong to undefined, subclass inherits parent class gets not same//output: property without this name




4, __set (string $name, mixed $value)

Called when assigning values to undefined variables

Header (' Content-type:text/html;charset=utf-8 ');      Class person{    private $name;    /**     * Assigns an undefined attribute parameter 1 = property name, parameter 2= value (any type)     * @param string $key     * @param mixed $val *    /function __set ( $key, $val) {        return ' give undefined attribute '. $key. ' Assignment '. $val;    }} $obj = new Person (); echo $obj->age = ' big pig ';//output: Big Pig

5, __call (string $name, array $arguments)

__call () is called when an inaccessible method, such as undefined or invisible, is invoked.

__callstatic (string $name, array $arguments)

__callstatic () is called when a non-accessible method is called in a static method, such as undefined or invisible.

6, __tostring ()

Called when an object is printed, this method is similar to the ToString method of Java, and when we print the object directly, we call back the function.

7, __clone ()

Called when an object is cloned.

8, __sleep ()

The serialize () function checks for the existence of a magic method __sleep. If present, the __sleep () method is called before the serialization operation is performed. This feature can be used to clean up an object and return an array that contains all the variable names in the object. If the method does not return anything, then NULL is serialized, resulting in a e_notice error. The __sleep method is often used to commit uncommitted data, or similar operations. At the same time, if you have some very large objects, do not need to save, this function is very useful.

9, __wakeup ()

In contrast to __sleep (), unserialize () checks for the existence of a __wakeup method. If present, the __wakeup method is called before the object data is prepared beforehand. __wakeup are often used in deserialization operations, such as re-establishing a database connection, or performing other initialization operations.

10, __isset ()

When Isset () or empty () is called on an undefined variable, __isset () is called.

11, __unset ()

Called when a property of an object is unset. such as: unset ($c->name).

12, __set_state ()

Called when the Var_export is called. Use the return value of __set_state as the return value of Var_export.

13, __autoload ()

When an object is instantiated, the method is called if the corresponding class does not exist. Simply put is the automatic loading of classes; When you try to use a class that is not organized by PHP, it looks for a __autoload global function. If this function is present, PHP invokes it with a parameter, which is the name of the class.

14, __invoke ()

The __invoke method is called automatically when an attempt is made to invoke an object in a way that invokes a function.

Magic constants:

The current line number in the __line__ file.

The full path and file name of the __file__ file. If used in the included file, returns the file name that is included. From PHP 4.0.2, __file__ always contains an absolute path (if it is a symbolic connection, the resolved absolute path), and the previous version sometimes contains a relative path.

The directory where the __dir__ file resides. If used in the included file, returns the directory where the included files are located. It is equivalent to DirName (__file__). Unless it is a root directory, the name in the directory does not include the trailing slash. (New in PHP 5.3.0) =

__function__ function name (PHP 4.3.0 new addition). From PHP 5 This constant returns the name (case-sensitive) when the function is defined. In PHP 4, this value is always in lowercase letters.

The name of the __class__ class (PHP 4.3.0 new addition). From PHP 5 This constant returns the name of the class when it is defined (case-sensitive). In PHP 4, this value is always in lowercase letters.

The method name of the __method__ class (PHP 5.0.0 new addition). Returns the name of the method when it is defined (case-sensitive).

__NAMESPACE__ the name of the current namespace (case sensitive). This constant is defined at compile time (PHP 5.3.0 new)

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