PHP Object-Oriented Programming: Method for developing large PHP projects (5)
Author: Luis Argerich Translator: limodou
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:
--------------------------------------------------------------------------------
<? 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. 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.