The method for developing large PHP projects here describes the Object-Oriented Programming (OOP, Object Oriented Programming) in PHP ). We will show you how to reduce coding and improve quality by using some OOP concepts and PHP skills. Good luck!
The concept of object-oriented programming:
Different authors may have different ideas, but an OOP language must have the following aspects:
ABSTRACT Data Types and information Encapsulation
Inheritance
Polymorphism
In PHP, classes are encapsulated:
Code:
<? Php
Class Something {
// In the OOP class, the first character is usually uppercase.
Var $ x;
Function setX ($ v ){
// The method starts with lowercase words, and then uses uppercase letters to separate words, such as getValueOfArea ()
$ This-> x = $ v;
}
Function getX (){
Return $ this-> x;
}
}
?>
Of course, you can define it according to your preferences, but it is better to maintain a standard to make it more effective.
Data members are defined using the "var" declaration in the class. They have no type before assigning values to data members. A data member can be an integer, an array, an associated array, or an object.
A method is defined as a function in a class. When using a member variable of the class in a method, you should use $ this-> name. Otherwise, a method 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 to the object's member variable x (not a class), and then getX returns its value 5.
You can access data members by referencing classes like $ obj-> x = 6. This is not a good OOP habit. I strongly recommend that you use methods to access member variables. If you think of member variables as unmanageable and use methods only through object handles, you will be a good OOP programmer. Unfortunately, PHP does not support declaring private member variables, so bad code is also allowed in PHP.
Inheritance is easy to implement in PHP, as long as the extend keyword is used.
Code:
<? Php
Class Another extends Something {
Var $ y;
Function setY ($ v ){
$ This-> y = $ v;
}
Function getY (){
Return $ this-> y;
}
}
?>
The object of the "Another" class now has all the data members and methods of the parent class (Something), and adds its own data members and methods.
You can use
Code:
$ Obj2 = new Something;
$ Obj2-> setX (6 );
$ Obj2-> setY (7 );
PHP currently does not support multi-inheritance, so you cannot derive a new class from two or more classes.
You can redefine a method in a derived class. If we redefine the getX method in the "Another" class, we cannot use the getX method in "Something. If you declare a data member with the same name as the base class in the derived class, it will "hide" The data member of the base class when you process it.
You can define constructors in your class. A constructor is a method with the same name as a class name. It is called when you create a class object. For example:
Code:
<? Php
Class Something {
Var $ x;
Function Something ($ y ){
$ This-> x = $ y;
}
Function setX ($ v ){
$ This-> x = $ v;
}
Function getX (){
Return $ this-> x;
}
}
?>
Therefore, you can create an object:
$ Obj = new Something (6 );
The constructor automatically assigns value 6 to the data variable x. Constructors and methods are common PHP functions, so you can use the default parameters.
Function Something ($ x = "3", $ y = "5 ")
Next:
$ 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
The default parameter uses the C ++ method, so you cannot ignore the value of Y. Instead, assign a value to X from left to right, if the input parameter is less than the required parameter, the default parameter is used for the input parameter.
When an object of A derived class is created, only its constructor is called, and the constructor of the parent class is not called. If you want to call the constructor of the base class, you must display the call in the constructor of the derived class. This can be done because all methods of the parent class in the derived class are available.
Code:
<? Php
Function Another (){
$ This-> y = 5;
$ This-> Something ();
// Display the call base class Constructor
}
?>
A good mechanism of OOP is to use abstract classes. Abstract classes cannot be instantiated and can only be provided to an interface of the derived class. Designers usually use abstract classes to force programmers to derive from the base class. This ensures that the new class contains some expected functions. There is no standard method in PHP,:
If you need this feature, you can define the base class and add the "die" call to its constructor to ensure that the base class cannot be instantiated, now, the "die" statement is added after each method (interface). Therefore, if a programmer does not overwrite the method in the derived class, an error is thrown. And because PHP is non-typed, you may need to confirm that an object comes from the derived class of your base class, then add a method to the base class to implement the Class Identity (return a certain id), and verify this value when you receive an object parameter. Of course, if an evil and bad programmer overwrites this method in a derived class, this method does not work, but generally the problem occurs frequently in the lazy programmer, rather than the evil programmer.
Of course, it is good to make the base class invisible to programmers, as long as the interface is printed out for their work.
No destructor in PHP.
Overload (different from overwriting) is not supported in PHP. In OOP, You can overload a method to implement two or more methods with the same name, but there are different numbers or types of parameters (depending on the language ). PHP is a loose language, so the type overload does not work, but the overload does not work by the number of parameters.
Sometimes the overload constructor in OOP is very good, so that you can create objects using different methods (passing different numbers of parameters ). In PHP
To implement it:
Code:
<? Php
Class Myclass {
Function Myclass (){
$ Name = "Myclass". func_num_args ();
$ This-> $ name ();
// Note that $ this-> name () is generally incorrect, but $ name is the name of the method to be called.
}
Function Myclass1 ($ x ){
Code;
}
Function Myclass2 ($ x, $ y ){
Code;
}
}
?>
Through additional processing in the class, using this class is transparent to users:
$ Obj1 = new Myclass ('1'); // call Myclass1
$ Obj2 = new Myclass ('1', '2'); // call Myclass2
Sometimes this is very useful.
Polymorphism
Polymorphism is a capability of an object. It determines the method of the object to be called at runtime Based on the passed object parameters. For example, if you have a figure class, it defines a draw method. The circle and rectangle classes are derived. In the derived class, you overwrite the draw method. You may also have a function that uses the x parameter, you can call $ x-> draw (). If you have polymorphism, the draw method that you call depends on the object type that you pass to this function.
Polymorphism is in an interpreted language like PHP (imagine which method should you call when a C ++ compiler generates such code? You don't know what type of objects you have. Well, this is not the point.) It is very easy and natural. Therefore, PHP certainly supports polymorphism.
Code:
<? Php
Function niceDrawing ($ x ){
// Assume this is a method of the Board class.
$ X-> draw ();
}
$ Obj = new Circle (3,187 );
$ Obj2 = new Rectangle (4, 5 );
$ Board-> niceDrawing ($ obj );
// Call the draw method of Circle
$ Board-> niceDrawing ($ obj2 );
// Call the draw method of Rectangle
?>
Use PHP for Object-Oriented Programming
Some purists may say that PHP is not a real object-oriented language. PHP is a hybrid language. You can use OOP or traditional procedural programming. However, for large projects, you may want/need to use pure OOP to declare classes in PHP, and only use objects and classes in your project.
As the project grows, it may be helpful to use OOP, And the OOP code is easy to maintain, easy to understand and reuse. These are software engineering.
. Applying these concepts in web-based projects will become the key to future website success.
PHP advanced OOP Technology
After reading the basic OOP concepts, I can show you more advanced technologies:
Serializing)
PHP does not support permanent objects. in OOP, permanent objects are objects that can maintain the state and function in the references of multiple applications, this means that you have the ability to save objects to a file or database and can load objects later. This is the so-called serialization mechanism. PHP has a serialization method, which can be called through an object. The serialization method can return the string representation of an object. However, serialization only saves the member data of the object without the package method.
In PHP4, if you serialize an object to the string $ s, release the object, and deserialize the object to $ obj, you can continue to use the object method! I do not recommend that you do this because (a) the document does not guarantee that this behavior can still be used in future versions. (B) This may lead to a misunderstanding when you save a serialized version to the disk and exit the script. When you run this script in the future, you cannot expect that when deserializing an object, the object method will also be there, because the string representation does not include the method at all.
All in all, PHP serialization is very useful for saving object member variables. (You can also serialize related arrays and arrays to a file ).
Example:
Code:
<? Php
$ Obj = new Classfoo ();
$ Str = serialize ($ obj );
// A few months later
// Input str from the disk
$ Obj2 = unserialize ($ str)
?>
You have recovered the member data, but do not include methods (as described in this document ). As a result, you can only use $ obj2-> x to access member variables (you have no other way !) So do not try it at home.
There are some ways to solve this problem. I keep it because they are too bad for this concise article.
Use classes for data storage
A good thing for PHP and OOP is that you can easily define a class to operate on something and call the corresponding class whenever you want to use it. Suppose you have an HTML form. You can select a product by selecting the product ID. There is product information in the database. you want to display the product and its price. You have different types of products, and the same action may have different meanings for different products. For example, displaying a sound may mean playing it, but for other products, it may mean displaying an image in the database. You can use OOP or PHP to reduce coding and improve quality:
Define a product class, define its expected method (for example, display), and then define the class of each type of product, which is sent from the product class (SoundItem class, viewableItem class, etc.), overwrite the methods in the product class, and make them act as you want.
Name the class according to the type field of each product in the database. A typical product table may have (id, type, price, description, and other fields )... in the processing script, you can retrieve the type value from the database and instantiate an object named type:
Code:
<? Php
$ Obj = new $ type ();
$ Obj-> action ();
?>
This is a very good feature of PHP. You can call the $ obj display method or other methods without considering the object type. With this technology, you do not need to modify the script to add a new type of object, but add a class to process it.
This function is very powerful, as long as you define methods, instead of considering the types of all objects, implement them in different classes according to different methods, and then use them for any objects in the main script, no if... else, there is no need for two programmers, just happy.
Now you agree that programming is easy, maintenance is cheap, and reusable is true?
If you manage a group of programmers, it is very easy to assign jobs. Each person may be responsible for a type of object and the class that processes it.
You can use this technology to achieve internationalization and apply the corresponding classes based on the language fields selected by the user.
Copy and clone
When you create a $ obj object, you can use $ obj2 = $ obj to copy the object. The new object is a copy of $ obj (not a reference ), therefore, it has the status of $ obj at that time. Sometimes, you just want to generate a new object like the obj class. You can use the new statement to call the class constructor. PHP can also be implemented through serialization and a base class, but all other classes must be derived from the base class.
Enter dangerous area
When you serialize an object, you will get a string of a certain format. If you are interested, you can call it. Among them, there is a class name in the string (Great !), You can take it out, such:
Code:
<? Php
$ Herring = serialize ($ obj );
$ Vec = explode (':', $ herring );
$ Nam = str_replace ("\" ",'', $ vec [2]);
?>
So suppose you have created a "Universe" class and forced all classes to be extended from universe. You can define a clone method in universe, as shown below:
Code:
<? Php
Class Universe {
Function clone (){
$ Herring = serialize ($ this );
$ Vec = explode (':', $ herring );
$ Nam = str_replace ("\" ",'', $ vec [2]);
$ Ret = new $ nam;
Return $ ret;
}
}
// Then
$ Obj = new Something ();
// Extend from Universe
$ Other = $ obj-> clone ();
?>
What you get is a new Something class object, which is the same as the object created by calling the constructor using the new method. I don't know if this is useful to you, but the Universe class can know that the name of a derived class is a good experience. Imagination is the only restriction. (Source: Flash)