Object-oriented programming of PHP

xiaoxiao2021-03-06  41

Object-oriented programming:? Different authors may not be the same, but an OOP language must have the following aspects: Abstract data type and information package? Inherit? Polymorphism? In PHP is through class to complete package :?

Class? Something? {? //? In the OOP class, usually the first character is uppercase? Var? $ x ;? function? setX ($ V)? {? //? method starts to lowercase words, then use uppercase Letters to separate words, such as getValueofarea ()? $ This-> x = $ v ;?}? Function? GetX ()? {? Return? $ This-> x ;?}?}? Of course you can press your own preference That is defined, but it is best to maintain a standard, which will be more effective. Data members are defined using the "VAR" declaration in the class. They are not type before assigning the data member. A data member can be an integer, an array, a associated array (Associative® Array) or an object. The method is defined in the form of a function in the class. When you access a class member variable in the method, you should use $ this-> name, otherwise it can only be a local variable. • Use the new operator to create an object:? $ Obj = new? Something; then you can use the member function to pass:? $ Obj-> setx (5); $ see = $ obj-> getx () ;? In this example, the SETX member function assigns 5 assignments to the object of the object X (not class), and then getx returns its value 5. You can use: $ OBJ-> X = 6 to access data members through class reference methods, which is not a good OOP habit. I strongly recommend access to member variables through way. If you regard the member variables as uncomfortable, you will be a good OOP programmer by using the object handle. Unfortunately, PHP does not support statement of private member variables, so bad code is also allowed in PHP. Inheriting is easy to implement in PHP, just use the extend keyword. ?

Class? Another? EXTENDS? Something? {? var? $ y ;? function? sety ($ v)? {? $ this-> y = $ v ;?}?

Function? get ()? {? Return? $ this-> y ;?}?} • Objects of the ANOTHER class now have all the data members and methods of the parent class, and they also have their own Data members and methods. ? $ Obj2 = new? Something; $ obj2-> setX (6); $ OBJ2-> setY (7) ;? PHP now does not support multiple inheritance, so you can't be from two or two The above class is derived from a new class. You can define a method in derived class, if we have defined the getx method in the "Another" class, we can't make it? Use the Getx method in "Something". If you declare a data member with the same name with the Batch in the derived class, then when you handle it? It will "hide" the data of the base class. • You can define constructor in your class. The constructor is a method with the same name as the class, when you create a class object, for example:?

Class? Something? {? var? $ x ;? function? Something ($ y)? {? $ this-> x = $ y ;?}? Function? setX ($ V)? {? $ this-> x = $ V;?}? Function? getX ()? {? Return? $ this-> x ;?}?}? So you can create an object, pass:? $ obj = new? Something (6) ;? constructor The 6 is automatically assigned to the data variable x. The constructor and methods are ordinary PHP functions, so you can use the default parameters. ? Function? Something ($ x = "3", $ y = "5")? then:? $ obj = new? Something ();? //? x = 3? and? y = 5? $ obj = new ? Something (8);? //? X = 8? And? Y = 5? $ Obj = new? Something (8, 9);? //? X = 8? And? Y = 9? Default parameter The C method, so you cannot ignore the value of Y, and give x a default parameter, the parameter is assigned from left to right, if the incoming parameter is less than the required parameter, the default parameters will be used. • When a derived object is created, only its constructor is called, the parent class's constructor is not called, if you want to call the constructor of the base class, you must display calls in the derived constructor . It can be done because all the methods in the derived class are available. Function? Another ()? {? $ this-> y = 5 ;? $ this-> Something () ;? // Display calling base class constructor?}? OOP a good mechanism is to use an abstract class. Abstract classes cannot be instantiated, only one interface to the derived class. Designers typically use abstract classes to force programmers to derive from the base class, which ensures that new classes contain some expectations. There is no standard method in PHP, but if you need this feature, you can use the "DIE" when it is defined by defining the base class, and after its constructor, the call is called, so that the base class can not be instantiated. Now add the "DIE" system after each method (interface), so if a programmer does not have overwriting methods in the derived class, an error will be triggered. And because PHP? Is non-type, you may need to confirm that an object is derived from your base class, then adds a method in the base class to the identity of the class (return to some kind of identity ID), and Check this value when you receive an object parameter. Of course, if an evil programmer covers this method in the derived class, this method does not work, but general problems are discovered in lazy programmers, not evil programmers. Of course, it is possible that the base class can not see the programmer, as long as the interface is printed out to do their work. There is no destructor in the PHP. • Overload (different from the overlay) is not supported in PHP. In OOP, you can overload a method to implement two or heavy methods have the same name, but there are different quantities or types of parameters (this depends on language). PHP? Is a loose type language, so it doesn't work by the type overload, however the number of times the number of parameters does not work. • Sometimes heavy load constructors in OOP are very good so you can create objects (passing different quantities) through different ways. The skill is implemented in PHP is:?

Class? myclass? {? function? myclass ()? {? $ name = "myclass" .func_num_args ();? $ this -> $ name () ;? // Note $ this-> name () is generally wrong But here $ name is a name that will be called method?}? Function? Myclass1 ($ x)? {? Code ;?}? Function? Myclass2 ($ x, $ y)? {? Code ;?}? }? By processing in the class, using this class is transparent to the user:? $ Obj1 = new? Myclass ('1');? // will call myclass1? $ Obj2 = new? Myclass ('1' , '2');? // will call myclass2? Sometimes this is very easy. • Polymorphism? Polygonity is an object of the object, which can determine which object of the call according to the passable object parameters at runtime. For example, if you have a class of Figure, it defines a method of DRAW. And derived the Circle and Rectangle class, in the derived class, you have overwritten the DRAW method, you may have a function, it wants to use a parameter x, and you can call $ x-> DRAW () ?. If you have polymorphism, which DRAW method calls depending on the type of object you passed to this function. Polymoritors in the interpretation language like PHP (imagine a C compiler to generate this code, which method you should call? You don't know what type of object you have, good, this is not a focus) is Very easy and natural. Therefore, PHP certainly supports polymorphism. ?

Function? NiceDrawing ($ x)? {? // assume this is a method of the Board class? $ x-> DRAW () ;?}? $ obj = new? circade (3,187); $ obj2 = new? Rectangle 4, 5); $ Board-> nicedrawing ($ obj) ;? // will call the Circle's DRAW method? $ Board-> nicedrawing ($ OBJ2) ;? // will call the Rectangle's DRAW method? Object Programming? Some "Puristers" may say PHP is not a real object-oriented language, which is a fact. PHP? Is a hybrid language, you can use OOP, you can also use traditional procedural programming. However, for large projects, you may want / need to use pure OOP to declare class in PHP? And use only objects and classes in your project. • As the project is getting bigger, using OOP may help, the OOP code is easy to maintain, easy to understand and reuse. These are the foundation of software engineering. Applying these concepts in web-based projects will become the key to the success of future websites. ? PHP's advanced OOP technology? After reading basic OOP concept, I can show you more advanced technology: Serializing? PHP does not support permanent objects, permanent objects in OOP can be in multiple The objects of the application are kept in the state and function, which means that it has the ability to save the object to a file or database, and the object can be loaded later. This is the so-called serialization mechanism. PHP? Have a serialization method that can be called by an object, and the serialization method can return the target of the object. However, serialization only saves the member data of the object without the method of private. ? In PHP4, if you sequence the object to the string $ s, then release the object, then reach the object to $ OBJ, you can continue to use the object! I don't recommend this to do this, because this behavior can still be used in future versions in the document. (b)? This may result in a misunderstanding, when you save a serialized version to the disk and exit the script. When running this script later, you cannot expect the object's method to the object, because the string is not included in the method. In summary, PHP? Serialization is very useful for the member variables of the object. (You can also serialize the associated arrays and arrays into a file). ? Example?:?

$ obj = new? classfoo (); $ str = serialize ($ obj);? // Save $ STR to disk? // After a few months? // Load STR? $ Obj2 = unserialize from disk? $ STR)? You have recovered member data, but do not include methods (in accordance with the documentation). This leads to only the only way to access member variables (you don't have any other way!) By using $ OBJ2-> X, don't try it at home. Have some way to solve this problem, I will stay it, because of this simple article, they are too bad. I would rather happily all of the full-sequence characteristics in the subsequent versions of PHP. • A very good thing to use classes for data storage PHP and OOP is that you can easily define a class to operate something, and whenever you want to use the corresponding classes. Suppose you have an HTML form, users can choose a product by selecting the product ID number. In the database, there is information, you want to display the product, showing its price, and so on. You have different types of products, and the same action may have a different meaning of different products. For example, displaying a sound may mean playing it, but for other kinds of products may mean displaying a picture in the database. You can use OOP or PHP to reduce encoding and increase quality: (SoundItem class, ViewableItem class, etc.), covering the way in the product class, making them action on your thoughts. • Name the type (Type) field of each product in the database, a typical product table may have (id,? Type,? Price,? Description, ", etc.) ... then in the processing script You can remove the TYPE value from the database, then instantiate a object called Type:?

$ obj = new? $ TYPE (); $ obj-> action (); this is a very good feature of PHP, you can call $ OBJ's display method or other method without considering the type of object. With this technology, you don't need to modify the script to add a new type of object, just add a class that handles it. This feature is very powerful, as long as the method is defined, not considering the type of all objects, implement them in different classes, and then use them to any object in the main script, no if ... Else, No need two programmers, only happy. Now you agree that programming is easy, maintenance is cheap, can you reuse it? • If you manage a group of programmers, allocation work is very simple, each person may be responsible for a type of object and processing it. • Internationalization can be achieved through this technology, and the corresponding classes can be applied according to the language field selected by the user, and so on. ? Copy and clone? When you create a $ OBJ object, you can copy objects through $ OBJ2 = OBJ, the new object is a copy of $ OBJ (not a reference), so it has $ OBJ at the time. status. Sometimes, you don't want this, you just want to generate a new object like an OBJ class, you can call the class constructor by using the New statement. In PHP can also be implemented by serialization, and a base class, but all other classes are derived from the base class. • Enter a dangerous area? When you serialize an object, you will get a string of a format. If you are interested, you can escape it, where there is a class name in the string (great!), You You can take it out, like:? $ HERRING = Serialize ($ OBJ); $ VEC = EXPLODE (':', $ HERRING); $ nam = str_replace ("/", '', $ vec [2 ]); So that you have created a "universe" class and force all classes must extend from the universe. You can define a Clone method in the universe?, As follows:?

Class? universe? {? function? clone ()? {? $ HERRING = Serialize ($ this); $ vec = evtern (':', $ HERRING); $ nam = str_replace ("/", '' $ VEC [2]); $ RET = new? $ nam ;? Return? $ RET;?}?}? // then? $ obj = new? Something () ;? // From Universe extension? $ otER = $ OBJ-> Clone ();? What you get is a new Something class object, which uses the New method to invoke the object created by the constructor. I don't know if this is useful for you, but the universe class You can know that the name of the derived class is a good experience. Imagination is the only limit.? Note: I use PHP4, I have written some things that may not work in PHP3.

转载请注明原文地址:https://www.9cbs.com/read-119393.html

New Post(0)