Magic methods in PHP

Source: Internet
Author: User

Next I will introduce all the magic methods in PHP. In fact, most of the following methods are familiar to a qualified PHP programmer. I will make a summary here, learn the records myself, and give an introduction to the students who are not familiar with these methods. We hope you can point out any omissions or errors. Most of the magic methods added by PhP5 are mentioned below. A small part already exists in PhP4, and a small part occurs after php5.1.0, this will be mentioned below.

_ Construct () and _ destruct ()
Construct _ construct () and destructor _ destruct (). I don't need to talk about them any more. I know them as a programmer. _ Construct () is called when the instance is created, __destruct () is called when the instance is destroyed. Note that even if you do not explicitly call unset to destroy an instance, it will be destroyed at the end of the script operation. Both methods can pass 0 or multiple parameters.

<? Phpclass o {public function _ construct () {echo 'Building instance';} public function _ destruct () {echo 'Destroy instance';} $ I = new O; unset ($ I); // whether or not this sentence exists does not affect the final output. _ Destruct () will always be called // output // building instance // destroy instance?>

_ Get, _ set, _ isset, _ unset
When performing operations on an attribute, if this attribute is not available (does not exist, or the current environment cannot call this attribute, for example, calling a private attribute of the parent class in a subclass ), call one of the above methods. What method is called is based on the operation on the attribute. Note: in PHP 5.0. *, the four methods must be public.
_ Get
Trigger event: Call attribute
Parameter 1: name of the called Property
Example:

<? Phpclass o {protected function _ Get ($ var) {return 'no Member :'. $ var ;}$ I = new O (); echo $ I-> name; // output no member: Name?>
<? Phpclass o {private $ name = 'surfchen '; // note the private protected function _ Get ($ var) {return 'no Member :'. $ var ;}} class Child extends o {function test () {echo $ this-> name ;}}$ c = new child (); echo $ C-> test (); // output no member: Name?>

_ Set
Trigger event: assign a value to an attribute
Parameter 1: name of the called Property
Parameter 2: Value
Example:

<? Phpclass o {protected function _ set ($ var, $ Val) {echo 'setting '. $ var. 'to '. $ Val. "/N" ;}}$ c = new O (); echo $ C-> name = 'wolfzeus';/* output: Setting name to wolfzeuswolfzeus */?>

_ Isset
Trigger event: Use isset to check whether a property exists
Parameter 1: name of the called Property
Example:

<? Phpclass o {protected function _ isset ($ var) {echo $ var. 'have not been set'; }}$ c = new O (); isset ($ C-> name);/* output: name have not been set */?>

_ Unset
Trigger event: unset an attribute (whether or not this attribute exists)
Parameter 1: name of the called Property
Example:

<? Phpclass o {protected function _ unset ($ var) {echo $ var. 'Is unset' ;}}$ c = new O (); unset ($ C-> name);/* output: Name is unset */?>

_ Call ($ func, $ para)
If the method of an object does not exist, the _ call ($ func, $ para) method is called. This method must have two parameters: the first is the name of the called method, and the second is a parameter array of the called method. It should be noted that when you call the private method of the parent class in a subclass or call the non-protect method of the class in an instance, _ call () is not called (), this is a difference between attribute operation methods such as _ call and _ get.

<? Phpclass o {protected function _ call ($ func, $ para) {echo 'no method :'. $ func. "/N ". 'with below parameters :'. "/N"; print_r ($ para) ;}}$ c = new O (); echo $ C-> getnames ('grammer ', 'geek '); /* output: No method: getnameswith below parameters: array ([0] => programmer [1] => geek) */?>

_ Sleep (), _ wakeup ()
_ Sleep is called when serialization (serialize) is an instance, __wakeup () is called when deserialization (unserialize. Note that _ sleep () must return an array or object (usually $ this is returned), and the returned value will be used as the serialized value. If this value is not returned, serialization fails. This also means that deserialization will not trigger the _ wakeup event. The following is an example.

<?phpclass o{public $a='xx';public $b='55';function __sleep(){echo "I am sleepy/n";return $this;}function __wakeup(){echo "wake up!/n";}}$i = new o;$si = serialize($i);echo "sleeping now...../n";print_r(unserialize($si));?>

_ Tostring ()
When an object is printed directly, this method is called.
Example:

<? Phpclass o {private $ name = 'surfchen '; public function _ tostring () {return $ this-> name ;}}$ I = new O; echo 'name :', $ I; // note that the name and variable $ I are connected with commas instead of periods?>

_ Set_state ()
Var_export can export a set as a string, which is some executable PHP code. In php5.1.0, a static method named _ set_state is introduced to make var_export support exporting object instances. When you use var_export to export an instance, the exported string contains the code that calls this static method. This method has a parameter, which is an array containing all member attributes of the exported instance. A little abstract. Let's look at the example below.

<? Phpclass o {public $ skill = 'php'; public static function _ set_state ($ ARR) {foreach ($ arr as $ k => $ V) {$ obj-> $ k = $ V;} return $ OBJ; }}$ I = new O; $ I-> age = 21; EVAL ('$ B = '. var_export ($ I, true ). ';'); // true indicates that var_export returns the exported string instead of printing it out. Print_r ($ B);/* output: stdclass object ([skill] => PHP [age] => 21) */?>

_ Clone ()
In PhP5, the value assignment between objects is always transmitted by address reference. For example, the following example will output 66 instead of 55.

<?phpclass o{public $age = 55;}$i   = new o;$i2 = $i;$i->age = 66;echo $i2->age;?>

If you want to pass the information using the actual value, you need to use the clone keyword.

<? Phpclass o {public $ age = 55 ;}$ I = new O; $ I2 = clone $ I; $ I-> age = 66; echo $ I2-> age; // output 55?>

However, the instance $ I is cloned here. If a member attribute of $ I is also an instance, this member attribute will still be passed to $ I2 as a reference method. For example:

<?phpclass o{public $age = 55;public $sub = null;}class o2{public $p=1;}$i   = new o;$i->sub=new o2;$i2 = clone $i;$i->sub->p=5;echo $i2->sub->p;?>

The final output is 5 rather than 1. That is to say, although $ I and $ I2 do not point to the same instance, their member attribute $ sub points to the same instance. At this time, we must use the _ clone method to copy $ sub. Add the _ clone () method to the O class. As follows:

<?phpclass o{public $age = 55;public $sub = null;public function __clone(){$this->sub=clone $this->sub;}}//......?>

In this way, when ECHO $ I2-> sub-> P;, the value 1 is output.
_ Autoload ()
When you create an instance, if the corresponding class does not exist, __autoload () will be executed. This function has a parameter for the class name corresponding to the instance to be created. In the following example, if/home/surfchen/project/auto. if php exists, the file require. Otherwise, an error of class test not found is printed and the current script is aborted.

<?phpfunction __autoload($class_name) {if ($class_name == 'test') {$class_file = '/home/surfchen/project/auto.php';}if (is_file($class_file)) {require_once $class_file;return true;}echo 'Class '.$class_name.' Not Found';exit();}$o=new test();echo $o->a;?>
Trackback tag (s): PHP-by: surfchen
 

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.