The Magic method in PHP is defined as a magic method that starts with two underscores, and these magic methods are very important in PHP, so let's look at examples of these magic methods.
Magic Method:
__construct (), the constructor of the class __destruct (), the class's destructor __call (), calls __callstatic () when an inaccessible method is called in an object, calls __get () when a non-accessible method is called in a static manner, When you get a member variable for a class, call __set (), set a member variable of a class when you call __isset (), call __unset () when calling isset () or empty () on an unreachable property, and call Unset () when you call a non-accessible property. __sleep (), when executing serialize (), first calls this function __wakeup (), executes Unserialize (), first calls the function __tostring (), the class is treated as a string when the response method __invoke (), This static method is called when the function is called when an object is called by the Response Method __set_state (), when the Var_export () 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
<?phpclass fileread{protected $handle = NULL; function __construct () { $this->handle = fopen (...);} function __destruct () { fclose ($this->handle);}}? >
These two methods can be extended during inheritance, for example:
<?phpclass 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.
<?phpclass methodtest{Public Function __call ($name, $arguments) { echo "calling object method ' $name '". Implode (', ', $arguments). "\ n"; The public static function __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 (),
The __get property is the automatic loading of the __get method when a property in the object is not present or is not a public property, and the parameter has only one name value, which is the Access object
The name of the property.
__set is when assigning a value to an attribute in an object, the __set method is automatically loaded if the property does not exist or is not a public property. There are two parameters, parameter 1 is the name of the Unreachable property in the Access object, and parameter 2 is the argument that will be passed to the assignment, either an array or a string
All have public visibility, non-static, and a little chestnut handy to understand:
<?php/** * Clear understanding of __get () __set () */class Example { //public properties $public = ' pub '; Protected-the attribute in the subclass can be protected $protected = ' Pro '; Private-only This class uses this property private $private = ' pri '; The __get () method is loaded automatically when a property in the Access object does not exist or is not a public attribute __get ($name) { return ' calls the __get () method: '. $name; } When assigning a value to an object's property, the __set () method is loaded automatically if the property does not exist or is not a public property () __set ($name, $value) { echo "\nname:". $ Name. ', Value: '. $value. ' \ n "; }} $example = new Example;echo ' <pre> '; Echo $example->public. " \ n "; Echo $example->protected." \ n "; Echo $example->private." \ n "; Echo $example->other." \ n "; Echo '
Echo ' Print public properties: '. $example->public;
__isset () and __unset ()
__isset () Call property in object or non-class call property when using Isset () method if no or non-public property
will automatically execute the Isset () method
__unset () invokes a property in an object or calls a property in a non-class using the unset () method if no or non-public property is
Automatic execution of a call to __unset () can delete a member property that cannot be called, and cannot be deleted if the method is not added to the class
object, and any private member in the
Together to give a small Li Zixian:
<?php /** * Examples of magic methods in Classes __isset () and __unset () */class Example {public $public; protected $protected; Private $private; Public Function __construct () { $this->public = ' pub '; $this->protected = ' Pro '; $this->private = ' pri '; } Public Function __isset ($var) { echo ' is here to view the property named '. $var through the __isset () method. \ n "; } Public Function __unset ($var) { echo ' here passes the __unset () method to destroy the property named '. $var. \ n "; }} $exa = new Example;echo ' <pre> '; Var_dump (Isset ($exa->public); echo "\ n"; Var_dump (Isset ($exa->protected) echo "\ n"; Var_dump (Isset ($exa->private)); echo "\ n"; Var_dump (Isset ($exa->novar)); echo "\ n"; Echo '
__sleep () and __wakeup ()
When we execute serialize () and unserialize (), these two functions are called 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:
<?phpclass connection{protected $link; private $server, $username, $password, $db; Public function __construct ($server, $username, $password, $db) { $this->server = $server; $this->username = $username; $this->password = $password; $this->db = $db; $this->connect (); } Private Function connect () { $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 () { $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 ()
This static method is called when the Var_export () export class is called.
<?phpclass a{Public $var 1, public $var 2; public static function __set_state ($an _array) { $obj = new A; $obj->var1 = $an _array[' var1 '); $obj->var2 = $an _array[' var2 '); return $obj; }} $a = new A; $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.
<?phppublic class Singleton {private static $_instance = NULL; Private constructor Method __construct () {} public static function getinstance () { if (Is_null (self::$_instance) { self::$_instance = new Singleton (); } return self::$_instance; } //Prevent clone instance Public function __clone () {die (' clone was 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__, Function name
__class__, the name of the class
__trait__,trait's name.
__method__, 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.