What this section explains
-
Cloning of objects
-
Traversal of objects
-
Serialization and deserialization of objects
-
Use of built-in standard classes
-
Use of traits
-
Related functions for classes and objects
-
PHP reflection mechanism
Objective
PHP's object-oriented is an important point of knowledge, and its thinking runs through the whole process of our development. In object-oriented, there are some knowledge points 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, then your reflection of PHP is also to master.
Cloning of objects
When we create an object, we will allocate a space in memory, the object name points to this space, before we talked about the assignment of the object, when an object changes the data inside, the other object's data will also change, because the assignment is equivalent to assigning an object identifier, and cloning is not the case.
<?phpclass person{public $name; public $age; public $sex; Public function __construct ($name, $age, $sex) { $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 (' Song Jiang ', ' 45 ', ' Male '); Echo ' <pre> '; $b = clone $a; $b name = ' Wu Song '; var_dump ($a); Var_dump ($b);
Results
Syntax for object cloning:
$ New Object = Clone $ on object;
As you can see from the above results, the data of one object changes and does not affect the data of another object. Object cloning generates a completely new object. Can be understood as follows:
In the Magic method of PHP There is a magic method and PHP cloning related to __clone (), when the copy is complete, if the Magic Method __clone () method is defined in the class, then the newly created is the copy generated object will call this __clone () method, In this method, you can make some changes to the properties if necessary.
If you do not want an object to be cloned, you can internally define the Magic Method __clone () method as private, if you are cloning, you will be prompted
Call to Private Peoson::__clone () from context '
Traversal of objects
Objects can also be traversed in PHP, and the traversal of an object can be interpreted as a traversal of the properties and values of an object. Traversal uses the loop body to the foreach. Basic syntax:
foreach (object name as $key = = $val) { //$key is the property name, $val is the property value}
<?php class person{public $name; public $age; Private $sex; Public function __construct ($name, $age, $sex) { $this, name = $name; $this, age = $age; $this, sex = $sex; }} $person = new Person (' Monkey King ', 256, ' Male '), foreach ($person as $key = = $value) { echo $key. ' = ' . $value. ' <br> ';} ....... The result ... name = Monkey King Age = 256
Object traversal can only be the property of the modifier is the public traversal, protected and private can not be accessed outside the class, so in the class outside the object traversal, with the two modifiers decorated with the property is not out, just like the code of the Sex property.
Serialization and deserialization of objects
In PHP, when the program executes a file, it will automatically free memory, the objects we create in the file, variables, etc., will disappear, if we create an object in a file, in another object to use this object, you can use the serialization of the object (serialize ()) and deserialization (Unserialize ()).
The serialization and deserialization of an object can be understood as converting an object into a string and storing it in a file, deserializing the object when it is used, and the object cannot be stored directly in the file.
:
a.php file, create an object and save:
<?php class person{public $name; public $age; Private $sex; Public function __construct ($name, $age, $sex) { $this, name = $name; $this, age = $age; $this, sex = $sex; }} $person = new Person (' Monkey King ', 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 writes a string to a file.
When the above code finishes, you can see that there is a person.txt file in the D drive, which is an object converted into a string.
b.php file, using the object in the a.php file person
<?php class person{public $name; public $age; Private $sex; Public function __construct ($name, $age, $sex) { $this, name = $name; $this, age = $age; $this, sex = $sex; } } Read a file to a string by file_get_contents this method. $str = file_get_contents (' d:person.txt '); To deserialize. $person = unserialize ($STR); Echo ' <pre> '; Var_dump ($person); ...... The result ... Object #1 (3) { ["name"]=> string (9) "Monkey King" ["Age "]=> Int () ["Sex": " Person ":p rivate]=> string (3)" Male " }
In b.php, a file is read to a string by file_get_contents (), and then deserialized by Unserialize (), but the resulting deserialized object is not a person object. So the declaration of the person class is copied into the file and automatically converted to the person object.
Serialization and deserialization of objects allows multiple files to share an object.
PHP built-in standard class
Sometimes we want to store some data in the form of object properties, and we don't want to define a class, we can consider using PHP's built-in standard class StdClass, which is a virtual class provided by the system and can be used directly without our definition.
<?php $person = new StdClass (); $person, name = ' Monkey King '; $person, age = 524; $person, sex = ' male '; Echo ' <pre> '; Var_dump ($person); ...... The result ... Object (StdClass) #1 (3) { ["name"]=> string (9) "Monkey King" ["Age"]=> int (524) ["Sex"]=> string (3) "Male" }
As we can see in the code above, there is no definition of the Stdclass class to be used.
Use of traits
Traits is a code reuse mechanism that is prepared for PHP-like single-inheritance languages. Trait to reduce the limitations of single-inheritance languages, developers are free to reuse the set of methods in separate classes within different hierarchies. It can be understood that a block of code is defined in traits and can be used in different classes.
Graphic:
Traits Use syntax:
Trait custom Name { //Extra defined code} use the format in the class using the custom name;
Code:
<?php //Use trait, custom name trait my_code{public function minus ($num 1, $num 2) { return $num 1-$num 2; } } Class a{public function Plus ($num 1, $num 2) { return $num 1 + $num 2; } } Class B extends a{ //code block defined with trait use my_code; } Class C extends a{use my_code; } Class D extends a{ } $b = new B (); $c = new C (); $d = new D (); echo $b Plus (UP); Echo ' <br> '; Echo $b-minus (2,1); Echo ' <br> '; echo $d Plus (UP); Echo ' <br> '; Echo $d-minus (2,1); ...... The result ... 3 1 3 Fatal error:call to undefined method D::minus () in D:\mywamp\Apache24\htdocs\zendstudio\ Yunsuanfu\staits.php on line 36
Class D does not use the trait code in the code above, so an error occurs when using the minus method.
When we write a function in trait like a function of a parent class, the trait code is the same, that is, the trait code takes precedence over the inherited class.
Class-to-object-related functions
In PHP, the system provides a series of functions to judge classes and objects. You can see a lot of functions from the Help documentation:
Here we only understand a few of the functions inside.
<?php class person{public $name; Public $age; Private $sex; Public function __construct ($name, $age, $sex) {$this, name = $name; $this, age = $age; $this, sex = $sex; The Public Function Showinfo () {echo ' name is: '. $this, name. ', Age is: '. $this, age. ', sex is: '. $this, sex. ' <br> '; }}//To determine whether the object was created, no creation returned true, and false was created. if (class_exists (' person ')) {$person = new person (' Tang Monk ', 25, ' Male '); Returns the class name of the object echo ' class name is: '. Get_class ($person). ' <br> '; Determine if the method exists. if (method_exists ($person, ' showinfo ')) {$person, showinfo (); }else{echo ' This method does not exist '; }//Determine if the attribute exists if (property_exists ($person, ' name ')) {echo $person, name; }else{echo ' attribute not present '; }}else{echo ' class does not exist '; } ...... Results...... The class name is: The person name is: Tang's monk, age is: 25, sex is: Male monk
By using class and object functions, we can guarantee the integrity of our code and capture the output of error information in a timely manner.
PHP reflection mechanism
In many programming languages there is the concept of reflection, which is simply understood through the class, getting the properties inside, methods, and even annotations, regardless of the type of the access modifier for the property and method can be obtained.
The full reflection API in PHP 5 adds the ability to reverse engineer classes, interfaces, functions, methods, and extensions. In addition, the reflection API provides a way to remove document comments from functions, classes, and methods. We generally do not use reflection in development, but in some cases the use of reflection can better deal with the problem, such as we need to write the framework of the underlying, expand the function, management of a large number of unknown classes.
Define a class that creates an object by reflection and invokes the method inside:
<?php class dog{public $name; protected $age; Private $food; Public function __construct ($name, $age, $food) { $this->name = $name; $this->age = $age; $this->food = $food; } Public function Cry ($sound) { echo ' <br> ' $this->name. ' The cry is. ' $sound; } } Use reflection to accomplish object creation and method invocation //1. Create a Reflection object $reflect _obj = new Reflectionclass (' Dog '); 2. Create an instance of a dog object by reflecting the object $dog = $reflect _obj->newinstance (' Rhubarb dog ', 4, ' ribs '); Echo ' <pre> '; Var_dump ($dog); 3. Call Method-use proxy mode. $reflect _method_cry = $reflect _obj->getmethod (' cry '); Echo ' <pre> '; Var_dump ($reflect _method_cry); 4. Proxy call Cry $reflect _method_cry->invoke ($dog, ' barking ');
Results:
In the above code, we create a reflected object through new, and the object of the class is obtained through the newinstance () method inside the reflected object. The method that gets inside can use the GetMethod () method of the Reflection object to return a method object Reflectionmethod class, which executes the method through the invoke () method inside. Here is just a basic introduction, you can find help documentation to learn more about reflective objects and methods.
Realization of TP controller scheduling by reflection
Demand:
There is a class indexaction, where the methods and access control modifiers are indeterminate, 1. If the index method is public, you can execute _before_index.2. If the _before_index method exists and is public, the method 3 is executed. Execute test Method 4. Then judge if there is no _after_index method, and it is public, execute the method
Code:
<?php class indexaction{Public Function index () {echo ' index<br> '; } public Function _before_index () {echo ' _before_index method execution <br> '; The Public Function test ($data) {echo ' data: '. $data. ' <br> '; } public Function _after_index () {echo ' _after_index method execution <br> '; }} if (Class_exists (' indexaction ')) {//create object $reflectionClass = new Reflectionclass (' indexaction '); Determines if index exists if ($reflectionClass-hasmethod (' index ')) {//Gets the Index method object $reflec _index _method = $reflectionClass-GetMethod (' index '); Determine if the modifier is public if ($reflec _index_method-isPublic ()) {//Determine if there is a _before_index method if ($reflectionClass-hasmethod (' _before_index ')) {$reflec _before_method = $reflectionClass GetMethod (' _before_index '); Determine if it is PUblic if ($reflec _before_method, IsPublic ()) {$reflec _before_method, in Voke ($reflectionClass-newinstance ()); Call the test () method $reflectionClass-GetMethod (' test '), Invoke ($reflectionClass-Newinstan CE (), ' This is the data of test '); Determine if there is a _after_index method if ($reflectionClass-hasmethod (' _after_index ')) { $reflec _after_method = $reflectionClass, GetMethod (' _after_index '); Determine if public if ($reflec _after_method-isPublic ()) {//execute _AF Ter_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 modified '; }}else{Echo ' Index method does not exist '; }}else{echo ' class name does not exist '; } ...... The result ... the _before_index method executes data: This is the test's _after_index method execution
In the above code, we can see that we are constantly in the judgment class there is no method, is not public modification, and then execute, we can use the idea of encapsulation, some common features extracted to write a function. So that we can optimize our code.
Optimized code:
<?php class indexaction{Public Function index () {echo ' index<br> '; } public Function _before_index () {echo ' _before_index method execution <br> '; The Public Function test ($data) {echo ' data: '. $data. ' <br> '; } public Function _after_index () {echo ' _after_index method execution <br> '; }} if (Class_exists (' indexaction ')) {$reflectionClass = new Reflectionclass (' indexaction '); Creates a Indexaction object. $indexAction = $reflectionClass-newinstance (); Execute ($reflectionClass, $indexAction, ' Index '); Execute ($reflectionClass, $indexAction, ' _after_index '); Execute ($reflectionClass, $indexAction, ' Test ', ' test-used data '); Execute ($reflectionClass, $indexAction, ' _after_index '); }else{Echo ' no Indexaction method '; }//Encapsulated function/** * [Execute description] encapsulation of the reflection. * @param [Type] $reflect _obj [Description] Reflection Object * @param [type] $worker [Description] Class object * @param [type] $name [description] Method name * @param [type] $canshu Parameters for [description] method * @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 used by Data:test _after_index method execution
You can see the encapsulation of functionality, which simplifies our code, while the code looks clearer.
Summarize
The object-oriented content of PHP is finished here, and the development of object-oriented thinking in development is a skill that must be mastered. At the same time, the object-oriented depth of understanding.
The above is the content of PHP, reflection, object serialization, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!