This article introduces object-oriented programming (OOP, ObjectOrientedProgramming) in PHP ). I will show you how to develop large PHP projects through PHP object-oriented programming (I)
This article introduces object-oriented Programming (OOP) in PHP ). I will show you how to connect
Using some OOP concepts and PHP skills to reduce coding and improve quality. 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:
-------------------------------------------------------------------------------- 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
It is an integer, an array, an associated array, or an object.
The method is defined as a function in the class. when using a member variable of the class 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 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
Methods to access member variables. If you think of the member variables as unprocessable and use the methods only through the object handle, 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.
Class Another extends Something {
Var $ y;
Function setY ($ v ){
$ This-> y = $ v;
}
Function getY (){
Return $ this-> y;
}
}
PHP object-oriented programming: method for developing large PHP projects (2)
The object of the "Another" class now has all the data members and methods of the parent class (Something), and adds its own data
Personnel and methods.
You can use
$ 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 in the derived class, when you process it,
It hides the data members of the base class.
You can define constructors in your class. A constructor is a method with the same name as a class name. when you create a class object, it is called
For example:
?> --------------------------------------------------------------------------------
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
If the input parameter is less than the required parameter, the default parameter is used.
When an object of a derived class is created, only its constructor is called, and the constructor of the parent class is not called.
Class constructor, 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 have
Is available.
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
The abstract class is used 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,
However:
If you need this feature, you can define the base class and add the "die" call to its constructor to ensure
Classes cannot be instantiated. now, the "die" statement is added after each method (interface). Therefore, if a programmer does not
OverWrite method will cause an error. And because PHP is non-typed, you may need to confirm that an object is derived from your base class.
Class, then add a method to the base class to implement the class identity (return a certain id), and verify when you receive an object parameter
This value. Of course, if an evil programmer overwrites this method in a derived class, this method does not work, but generally
The problem is often caused by laziness programmers, rather than evil programmers.
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.
PHP object-oriented programming: method for developing large PHP projects (3)
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
But there are different numbers or types of parameters (depending on the language ). PHP is a loose type language.
However, the number of parameters does not work.
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:
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.
With the draw method built, you may have another function that wants to use a parameter x and 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
It is very easy and natural to know what type of objects you own. Therefore, PHP certainly supports polymorphism.
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 it in PHP
Pure OOP declares classes, and only objects and classes are used 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 object-oriented programming: methods for developing large PHP projects (4)
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, which means
Objects can be saved to a file or database, and objects can be loaded later. This is the so-called serialization mechanism. PHP support
A serialization method can be called through an object. a serialization method can return a string representation of an object. However, serialization only saves
Object member data instead of 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
How to use objects! 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 cause a misunderstanding when you save a serialized version to the disk and exit the script. When you run this script later
It is not expected that the method of the object will also be there when deserializing an object, 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
File ).
?> --------------------------------------------------------------------------------
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 variable (you have no other methods !) 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.
I would be very pleased to welcome the full serialization feature in subsequent PHP versions.
PHP object-oriented programming: method for developing large PHP projects (5)
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 whenever you want
You can call corresponding classes when using them. Suppose you have an HTML form. you can select a product by selecting the product ID. Number
According to the product information in the database, you want to display the product and its price. You have different types of products and the same action
It may have different meanings for different products. For example, displaying a sound may mean playing it, but for other products
Indicates that an image in the database is displayed. You can use OOP or PHP to reduce coding and improve quality:
Define the class of a product, define the method it should have (for example: Display), and then define the class of each type of product, from the product
Classes (SoundItem class, ViewableItem class, and so on), override the methods in the product class, and make them act as you think.
Name the class based on the type field of each product in the database. a typical product table may have (id, type, price,
Description, and so on)... then, in the processing script, you can retrieve the type value from the database and instantiate
Object:
?> --------------------------------------------------------------------------------
This is a very good feature of PHP. you can call the $ obj display method or other methods without considering the object type. Use
In 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
So it has the status of $ obj at that time. Sometimes, you just want to generate a new one 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,
Some other classes must be derived from the base class.
Enter Dangerous area
When you serialize an object, you will get a string of some format. if you are interested, you can call it.
Class name (great !), You can take it out, such:
?> --------------------------------------------------------------------------------
So if you create a "Universe" class and force all classes to be extended from universe, you can
To define a clone method, as follows:
--------------------------------------------------------------------------------
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 am not
Know whether this is useful to you, but the Universe class can know that the name of the derived class is a good experience. Imagination is the only restriction.
Note: I use PHP4, and some of the things I write may not work under PHP3.
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.