Php magic function learning and application _ construct () _ destruct () _ get () and so on

Source: Internet
Author: User
Php magic function learning and application _ construct () _ destruct () _ get () and so on (1) the first magic method Php5.0 has provided us with a lot of object-oriented since its release? Especially, it provides us with a lot of easy-to-use magic methods. these magic methods can simplify my Php magic function learning and application _ construct () _ destruct () _ get () and so on

(1) first knowledge of magic methods
Php5.0 has provided us with many features since its release.Object? Features, especially providing us with a lot of easy-to-use magic methods that can simplify our coding and better design our system. Today, let's get to know the magic methods provided by php5.0.

1 ,__ construct () when instantiating an object, this method of this object is called first.

class Test{function __construct(){echo "before";}}$t = new Test();

?
The output is:

Start



 ?

// Output end


Do we know the php5 object model?Same as the class name? OfFunction? Is the construction of classesFunction?, If we define the structure at the same timeFunction? Php5 calls the construct () method by default.Function? Instead of calling similar namesFunction?, So _ construct () is used as the default structure of the class.Function?

2 ,__ destruct () this method is called when an object or object operation is terminated.

class Test{function __destruct(){echo "end";}}$t = new Test();

?
Will output
End


We can release resources at the end of the object operation.

3 ,__ get () is called when an attempt is made to read an attribute that does not exist.
If you try to read an attribute that does not exist in an object, PHP will give an error message. If you add the _ get method to the class, you can use thisFunction? Implement operations similar to reflection in java.

Class Test {public function _ get ($ key) {echo $ key. "nonexistent" ;}}$ t = new Test (); echo $ t-> name;

?

The output is as follows:
Name does not exist

4 ,__ set () is called when you try to write a value to an attribute that does not exist.

Class Test {public function _ set ($ key, $ value) {echo ''. $ key. "Value ". $ value ;}}$ t = new Test (); $ t-> name = "aninggo ";

?

The output is as follows:
Name value aninggo


5 ,__ call () this method is called when you try to call a method that does not exist in an object.

Class Test {public function _ call ($ Key, $ Args) {echo "the {$ Key} method you want to call does not exist. The parameter you passed in is: ". print_r ($ Args, true) ;}}$ t = new Test (); $ t-> getName (aning, go );

?

The program will output:
The getName method you want to call does not exist. The parameter is Array.
(
[0] => aning
[1] => go
)

6 ,__ toString () is called when an object is printed
This method is similar to the toString method of java. We call this method when we print the object directly.Function?

Class Test {public function _ toString () {return "print Test" ;}}$ t = new Test (); echo $ t;

?

When echo $ t; is run, $ t->__ toString () is called to output
Print Test

7 ,__ clone () is called when the object is cloned

Class Test {public function _ clone () {echo "I have been copied! ";}}$ T = new Test (); $ t1 = clone $ t;

?

Program output:
I have been cloned!


_ Sleep and _ wakeup



Serialize can include objects and convert them into continuous bytes data. you can save serialized variables in a file or transmit them over the network. then, the data is deserialized and restored to the original data. PHP can successfully store the attributes and methods of the objects defined before the objects of the deserialization class. sometimes you may need an object to be executed immediately after deserialization. for this purpose, PHP will automatically find the _ sleep and _ wakeup methods.

When an object is serialized, PHP calls the _ sleep method (if any ). after an object is deserialized, PHP calls the _ wakeup method. both methods do not accept parameters. the _ sleep method must return an array containing the attributes to be serialized. PHP will discard other attribute values. if the _ sleep method is not available, PHP will save all attributes.

Example 6.16 shows how to serialize an object using the _ sleep and _ wakeup methods. the Id attribute is a temporary attribute not intended to be retained in the object. the _ sleep method ensures that the id attribute is not included in the serialized object. when a User object is deserialized, the __wakeup method creates a new value for the id attribute. this example is designed to be self-sustaining. in actual development, you may find that objects containing resources (such as or data streams) need these methods.

Object serializationCODE: [Copy to clipboard] --------------------------------------------
  Id = uniqid ();} function _ sleep () {// do not serialize this-> id not serialized id return (array ("name "));} function _ wakeup () {// give user a unique ID $ this-> id = uniqid () ;}// create object to create an object $ u = new User; $ u-> name = "Leon"; // serialize it serializization note that the id attribute is not serialized, and the id value is discarded $ s = serialize ($ u ); // unserialize it deserialization id is re-assigned $ u2 = unserialize ($ s ); // $ u and $ u2 have different IDs $ u and $ u2 have different IDs print_r ($ u); print _ R ($ u2);?>
?


_ Set_state and _ invoke


The test code is as follows:


  $v)        {             $obj->$k = $v;        }        return $obj;    }}$a = new A;$a->name = 'cluries';$a->sex = 'female';eval('$b = ' . var_export($a, true) . ';');print_r($b);?>
??

Program output

object(A)#2 (2) {         ["name"]=>  string(7) "cluries"         ["sex"]=>  string(6) "female"}

Draw the following conclusion: __set_state is used to copy an object, and it can be defined in _ set_state to make some changes to the copied object during object copying. Unlike _ clone, _ set_state can accept parameters, __set_state is more powerful! Although I personally think this is not very useful =!



Then let's talk about _ invoke:
The manual has a very conspicuous one:Note: This feature is available since PHP 5.3.0 .?

The __invoke method is called when a script tries to call an object as a function.

_ Will the invoke method be called when the code tries to use the object as a function? A little strange. what is the use of this function?
Next, let's look at the provided example:


  
?


Program output:

int(5)bool(true)

Actually, the object is used as a function...


_ Autoload



In PHP5, there is a method: _ autoload (). In short, it is the automatic loading of classes;

When you try to use a class that is not organized by PHP, it will look for a global function of _ autoload. if this function exists, PHP uses a parameter to call it. the parameter is the name of the class.

Let's perform a simple test.


First, create a file named "Test_autoload.php:


<? Php/*** test _ autoload method **/class Test_autoload {public function _ construct () {echo "Test_autoload." ;}}?>
?

Note the class name ?, Create a file and rewrite the _ autoload () method. Here we assume it is "test. php ";


<? Php/*** rewrite _ autoload method */function _ autoload ($ class) {include $ class. '. php ';} $ test = new Test_autoload (); unset ($ test);?>
?

The final result is:Test_autoload.



------------------------------------------------
8. By the way, we will introduce several COOl labs in php5.Function?
(1 ). Runkit_method_rename
??? ThisFunction? We can dynamically change the calledFunction? OfName?.

Class Test {function foo () {return "foo! ";}} Runkit_method_rename ('test', // class name 'foo', // actually called function 'bar' // Display called function); echo Test :: bar ();

?

The program will output
 
Foo!

(2) runkit_method_add

ThisFunction? Can be dynamically added to the classFunction?


Class Test {function foo () {return "foo! ";}} Runkit_method_add (Test, // class name 'Add', // New function name '$ num1, $ num2 ', // input the parameter 'return $ num1 + $ num2; ', // The executed code RUNKIT_ACC_PUBLIC); // call echo $ e-> add (12, 4 );

?

(3) runkit_method_copy
You can setFunction? Copy to Class B andFunction? Rename


Class Foo {function example () {return "foo! ";}} Class Bar {// empty class} // Copy runkit_method_copy ('bar', 'Baz', 'foo', 'example '); // execute the Copy function echo Bar: baz ();

?

(4) runkit_method_redefine
Dynamic modificationFunction? Return value
ThisFunction? We can easily implement the MOCK test on the class! Is it COOL?


Class Example {function foo () {return "foo! ";}}// Create a test object $ e = new Example (); // output echo" Before: "Before the test object :". $ e-> foo (); // modify the return value runkit_method_redefine ('example ', 'foo', '', 'Return" bar! "; ', RUNKIT_ACC_PUBLIC); // execute echo" After: ". $ e-> foo ();

?


(5) runkit_method_remove
ThisFunction? It's easy.Name? As you can see, dynamically remove from the classFunction?

Class Test {function foo () {return "foo! ";} Function bar () {return" bar! ";}} // Remove the foo function runkit_method_remove ('test', 'Foo'); echo implode ('', get_class_methods ('test '));

?

Program output
Bar

?

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.