PHP basic tutorial 13 reflection and object serialization

Source: Internet
Author: User
Tags object serialization traits custom name
This section describes the serialization and deserialization of cloned objects. the use of traits and the PHP Reflection mechanism of related functions of objects.

Content described in this section
  • Object cloning

  • Object traversal

  • Object serialization and deserialization

  • Use of built-in standard classes

  • Use of traits

  • Class and object-related functions

  • PHP Reflection mechanism

Preface

PHP object-oriented is an important knowledge point, and its idea runs through the entire process of our development. There are still some knowledge points in object orientation that need to be understood. the characteristics of object cloning and object traversal, object serialization and deserialization. if you want to write a PHP framework, so you need to know the reflection of PHP.

Object cloning

When we create an object, we will allocate a space in the memory. the object name points to this space. we mentioned previously that the object is assigned a value. When an object modifies the data in it, the data of another object also changes, because the value assignment is equivalent to assigning a copy of the object identifier, and cloning is not like this.

 Name = $ name; $ this-> age = $ age; $ this-> sex = $ sex;} public function getName () {return $ this-> name ;} public function getAge () {return $ this-> age;} public function getSex () {return $ this-> sex ;}$ a = new Person ('songjiang ', '45', 'male'); echo'
'; $ B = clone $ a; $ B-> name = 'wusong'; var_dump ($ a); var_dump ($ B );

Result

In the PHP magic method, there is a magic method related to PHP cloning _ clone (). when the replication is complete, if the magic method _ clone () is defined in the class () the _ clone () method is called for the newly created object, that is, the copied object. In this method, you can change the attributes if necessary.

If you do not want to clone an object, you can internally define the magic method _ clone () as private. if you are cloning an object, a message is displayed.

Call to private Peoson::__clone() from context ''
Object traversal

Objects can also be traversed in PHP. object traversal can be understood as displaying the attributes and values of an object. Traverse the loop body using foreach. Basic syntax:

Foreach (object name as $ key => $ val) {// $ key is the attribute name, $ val is the attribute value}
  Name = $ name; $ this-> age = $ age; $ this-> sex = $ sex; }}$ person = new Person ('Sun Wukong ', 256, 'male'); foreach ($ person as $ key => $ value) {echo $ key. '= '. $ value.'
';} ...... Result ...... name = Sun Wukong age = 256

Objects can only be traversed using the public modifier. protected and private cannot be accessed outside the class. Therefore, objects can be traversed outside the class, the attributes modified with these modifiers cannot be obtained, just like the sex attribute of the code above.

Object serialization and deserialization

In PHP, when the program executes a file, the memory will be automatically released, and the objects and variables created in the file will disappear, if we create an object in a file and want to use this object in another object, we can use the serialization (serialize () of the object ()) and deserialization (unserialize ()).

Object serialization and deserialization can be understood as converting an object into a string and saving it in a file. When an object is used, the object is deserialized to obtain the object. the object cannot be directly stored in the file.

:

A. php file, create an object and save it:

  Name = $ name; $ this-> age = $ age; $ this-> sex = $ sex; }}$ person = new Person ('Sun Wukong ', 256, 'male'); // use the file_put_contents () function to write a string to the file file_put_contents ('d: person.txt ', serialize ($ person ));

The above code file_put_contents () function is to write a string into a file.
After executing the code of the notebook, you can see that the dashboard has a person.txt file, which is an object converted into a string.

B. php file. use the object "person" in the. php file.

  Name = $ name; $ this-> age = $ age; $ this-> sex = $ sex;} // read a file to a string using the file_get_contents method. $ Str = file_get_contents ('d: person.txt '); // deserialization. $ Person = unserialize ($ str); echo'
'; Var_dump ($ person );...... result ...... object (Person) #1 (3) {["name"] => string (9) "Sun Wukong" ["age"] => int (256) ["sex ": "Person": private] => string (3) "male "}

In B. in php, a file is read to a string through the file_get_contents () method, and then deserialized through unserialize (). However, the deserialized object is not a person object, so copy and paste the person class declaration in the file and convert it to the person object automatically.

Object serialization and deserialization allow multiple files to share an object.

PHP built-in standard class

Sometimes we want to store some data in the form of object attributes, and we do not want to define a class. we can consider using the PHP built-in standard class stdClass, this is a virtual class provided by the system and can be directly used without being defined.

   Name = 'Sun wukong'; $ person-> age = 524; $ person-> sex = 'male'; echo'
'; Var_dump ($ person );...... result ...... object (stdClass) #1 (3) {["name"] => string (9) "Sun Wukong" ["age"] => int (524) ["sex"] => string (3) "male "}

In the code above, we can see that the class stdClass is not defined.

Use of Traits

Traits is a code reuse mechanism prepared for a single inheritance language similar to PHP. Trait allows developers to freely reuse method sets in independent classes in different hierarchies to reduce the restrictions of a single inheritance language. It can be understood that a block of code is defined in traits and can be used in different classes.

Illustration:

Traits syntax:

Trait custom name {// additional defined code} use the format use custom name in the class;

Code:

    Plus (1, 2); echo'
'; Echo $ B-> minus (2, 1); echo'
'; Echo $ d-> plus (1, 2); echo'
'; Echo $ d-> minus (2, 1 );...... result ...... 3 1 3 Fatal error: Call to undefined method D: minus () in D: \ mywamp \ Apache24 \ htdocs \ zendstudio \ yunsuanfu \ staits. php on line 36

In the above code, Class D does not use the trait code, so an error occurs when the minus method is used.

When the functions written in trait are the same as those of the parent class, the trait code prevails, that is, the trait code has a higher priority than the inherited class.

Class and object-related functions

In PHP, the system provides a series of functions to judge classes and objects. You can see many functions in the help document:

Here, we only need to understand the functions.

    Name = $ name; $ this-> age = $ age; $ this-> sex = $ sex;} public function showInfo () {echo 'name :'. $ this-> name. ', age :'. $ this-> age. ', gender :'. $ this-> sex.'
';}} // Determines whether an object is created. If no object is created, true is returned. If yes, false is returned. If (class_exists ('person ') {$ Person = new person ('tangsan', 25, 'male'); // The echo class name of the returned object is: '. get_class ($ person ).'
'; // Determines whether a method exists. If (method_exists ($ person, 'showinfo') {$ person-> showInfo ();} else {echo 'this method does not exist ';} // Determine whether the property exists if (property_exists ($ person, 'name') {echo $ person-> name;} else {echo 'Property does not exist ';}} else {echo 'class does not exist ';}...... result ...... class name: Person name: Tang Seng, Age: 25, Gender: Male Tang Seng

Using classes and object functions can ensure the integrity of our code and capture and output error information in a timely manner.

PHP Reflection mechanism

Reflection is a concept in many programming languages. a simple understanding of reflection is to obtain attributes, methods, and even comments in a class, no matter what type of access modifier the attribute and method can be obtained.

PHP 5 has a complete reflection API and adds the reverse engineering capability for classes, interfaces, functions, methods, and extensions. In addition, the reflection API provides methods to retrieve document comments in functions, classes, and methods. However, we generally do not use reflection in development, but in some cases, reflection can better handle problems. for example, we need to write the underlying framework and expand functions, manage a large number of unknown classes.

Define a class, create an object through reflection, and call the methods in it:

    Name = $ name; $ this-> age = $ age; $ this-> food = $ food;} public function cry ($ sound) {echo'
'. $ This-> name. 'call is. '. $ sound ;}/// use reflection to create an object and call the method. // 1. create a reflection object $ reflect_obj = new ReflectionClass ('dog'); // 2. use a reflection object to create a Dog object instance $ dog = $ reflect_obj-> newInstance ('big yellow dog', 4, 'spareri'); echo'
'; Var_dump ($ dog); // 3. call method-use proxy method. $ reflect_method_cry = $ reflect_obj-> getMethod ('cry'); echo'
'; Var_dump ($ reflect_method_cry); // 4. call the proxy cry $ reflect_method_cry-> invoke ($ dog, 'wangwang ');

Result:

In the code above, we created a reflection object through new, and obtained the class object through the newInstance () method in the reflection object. You can use the getMethod () method of the reflected object to obtain the method. the returned result is a ReflectionMethod class of the method object, which is executed using the invoke () method. Here is just a basic introduction. you can find the help document to learn more about reflection objects and methods.

Reflection for TP controller scheduling

Requirements:

There is a class IndexAction in which the methods and access control modifiers are uncertain. 1. if the index method is public, run _ before_index.2. if the _ before_index method exists and is public, execute this method 3. execute test method 4. check whether the _ after_index method is public. run this method.

Code:

      ';} Public function _ before_index () {echo' _ before_index method execution
';} Public function test ($ data) {echo 'data:'. $ data .'
';} Public function _ after_index () {echo' _ after_index method execution
';}} If (class_exists ('indexaction') {// create an object $ reflectionClass = new ReflectionClass ('indexaction '); // Determine whether the index exists if ($ reflectionClass-> hasMethod ('index') {// Obtain the index method object $ reflec_index_method = $ reflectionClass-> getMethod ('index '); // Determine whether the modifier is public if ($ reflec_index_method-> isPublic () {// Determine whether the _ before_index method is available if ($ reflectionClass-> hasMethod ('_ before_index ')) {$ reflec_before_method = $ reflectionClass-> getMethod ('_ before_index'); // determines whether it is public if ($ reflec_before_method-> isPublic ()) {$ reflec_before_method-> invoke ($ reflectionClass-> newInstance (); // call the test () method $ reflectionClass-> getMethod ('test ') -> invoke ($ reflectionClass-> newInstance (), 'This is the test data '); // Determine whether the _ after_index method is available. if ($ reflectionClass-> hasMethod ('_ after_index') {$ reflec_after_method = $ reflectionClass-> getMethod ('_ after_index '); // determine whether it is public if ($ reflec_after_method-> isPublic () {// execute the _ after_index method $ reflec_after_method-> invoke ($ reflectionClass-> newInstance ());} else {echo '_ after_index is not public modified';} else {echo 'No _ after_index method';} else {echo '_ before_index modifier is not public ';}} else {echo 'No _ before_index method';} else {echo 'index method is not public modifier ';} else {echo 'index method does not exist ';}} else {echo 'class name does not exist ';}...... result ....... the _ before_index method executes data: this is the test data.

In the code above, we can see that we constantly judge whether there is a certain method in the class, whether it is a public modifier, and then execute it. we can use the encapsulated idea, extract common features and write them into a function. To optimize our code.

Optimized code:

      ';} Public function _ before_index () {echo' _ before_index method execution
';} Public function test ($ data) {echo 'data:'. $ data .'
';} Public function _ after_index () {echo' _ after_index method execution
';}} If (class_exists ('indexaction') {$ reflectionClass = new ReflectionClass ('indexaction'); // Create an IndexAction object. $ IndexAction = $ reflectionClass-> newInstance (); execute ($ reflectionClass, $ indexAction, 'index'); execute ($ reflectionClass, $ indexAction, '_ after_index '); execute ($ reflectionClass, $ indexAction, 'test', 'Data used by test'); execute ($ reflectionClass, $ indexAction, '_ after_index ');} else {echo 'no IndexAction method';} // encapsulated function/*** [execute description] encapsulate reflection. * @ Param [type] $ reflect_obj [description] reflection object * @ param [type] $ worker [description] class object * @ param [type] $ name [description] method name * @ param [type] $ canshu [description] method parameter * @ return boolean [description] */function execute ($ reflect_obj, $ indexAction, $ name, $ param = '') {if ($ reflect_obj-> hasMethod ($ name) {$ method = $ reflect_obj-> getMethod ($ name ); if ($ method-> isPublic () {$ method-> invoke ($ indexAction, $ param);} else {echo $ name. 'Not public';} else {echo $ name. 'method does not exist ';}}...... result ..... the index _ after_index method executes the data: the data _ after_index method used by test.

We can see that functional encapsulation can simplify our code while the code looks clearer.

Summary

PHP's object-oriented content has been fully discussed here. it is essential to master the skills to use the object-oriented idea in development. At the same time, we also need to have a deep understanding of object-oriented.

The above is PHP, reflection, object serialization content. For more information, please follow the PHP Chinese network (www.php1.cn )!

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.