Method 1 for developing large-scale PHP projects
This article introduces object-oriented programming (OOP, Object Oriented Programming) in PHP. I'll show you how to reduce coding and improve quality by using some OOP concepts and PHP tricks. Good luck!
The concept of object-oriented programming:
Different authors may have different opinions, but an OOP language must have the following aspects:
Abstract data types And information encapsulation
Inheritance
Polymorphism
In PHP, encapsulation is completed through classes:
------ ---------------------------------------------
class Something {
// In OOP classes, usually the first character is uppercase
var $x;
function setX($v) {
// The method starts with a lowercase word, and then uses uppercase letters to separate the words, such as getValueOfArea()
$this->x=$v;
}
function getX() {
return $this->x;
}
}
?>----------------------------------------- -------------
Of course you can define it according to your own preferences, but it is best to maintain a standard, which will be more effective.
Data members are defined in the class using the "var" declaration. Before the data members are assigned a value, they have no type. A data member can
be an integer, an array, an associative array, or an object.
Methods are defined as functions in the class. When accessing class member variables in a method, you should use $this->name, otherwise for a method, it can only be local variable.
Use the new operator to create an object:
$obj=new Something;
You can then use member functions via:
$obj- >setX(5);
$see=$obj->getX();
In this example, the setX member function assigns 5 to the member variable of the object x (not of the class), then getX returns its value 5.
You can access data members through class references like: $obj->x=6. This is not a good OOP habit. I strongly recommend accessing member variables through methods. You will be a good OOP programmer if you treat member variables as unmanipulable and use methods only through object handles. Unfortunately, PHP does not support declaring private member variables, so bad code is allowed in PHP.
Inheritance is easy to implement in PHP, just use the extend keyword.
-------------------------------------------------- ---------
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), plus its own data members and methods.
You can use
$obj2=new Something;
$obj2->setX(6);
$obj2->setY( 7);
PHP currently does not support multiple inheritance, so you cannot derive new classes 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 in a derived class with the same name as the base class, it will "hide" the base class data member when you deal with it.
You can define constructors in your class. The constructor is a method with the same name as the class name. It is called when you create an object of the class, 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); The
constructor will automatically assign 6 to the data variable x. Constructors and methods are normal PHP functions, so you can use 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
The default parameters use the C++ method, so you cannot ignore the value of Y and give X a default parameter. The parameters are assigned from left to right. If
When the parameters passed in are less than the required parameters, the default parameters will be 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. If you want to call the constructor of the base class
function, you must explicitly call it in the constructor of the derived class. This can be done because all methods of the parent class are available in the derived class.
----------------------------------------- ------------
function Another() {
$this->y=5;
$this- >Something();
//Display calling base class constructor
}
?>---------- ----------------------------------------
OOP is very A good mechanism is to use abstract classes. Abstract classes cannot be instantiated and can only provide an interface to derived classes. Designers often use abstract classes to force programmers to derive from a base class, thus ensuring that the new class contains some desired functionality. There is no standard method in PHP, but:
If you need this feature, you can define the base class and add the "die" call after its constructor, so that it can be guaranteed The base class is not instantiable, and now a "die" statement is added after each method (interface), so if a programmer does not override the method in a derived class, an error will be raised. And because PHP is untyped, you may need to confirm that an object is a derived class from your base class, then add a method in the base class to define the identity of the class (return some kind of identification id), and in your Check this value when receiving an object parameter. Of course, if an evil programmer overrides this method in a derived class, this method will not work, but generally the problem is found in lazy programmers, not evil programmers.
Of course, it's nice to be able to keep the base classes invisible to programmers, who can just print out the interfaces and do their job.
There is no destructor in PHP.
Methods for developing large PHP projects (3)
Overloading (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 different numbers or types of parameters (depending on the language). PHP is a loosely typed language, so overloading by type does not work, but overloading by different number of parameters does not work either.
Sometimes it's good to overload constructors in OOP so that you can create objects in different ways (passing different numbers of arguments). The trick to implement it in PHP is:
---------------------------------- ---
class Myclass {
function Myclass() {
$name="Myclass".func_num_args();
$this->$name();
//Note that $this->name() is generally wrong, but here $name is the name of a method that will be called
}
function Myclass1 ($x) {
code;
}
function Myclass2($x,$y) {
code;
}
}
?>
Using this class is transparent to the user through additional processing in the class:
$obj1= new Myclass('1'); //Myclass1 will be called
$obj2=new Myclass('1','2'); //Myclass2 will be called
Sometimes this is very useful .
Polymorphism
Polymorphism is an ability of an object. It can decide which object method to call based on the passed object parameters at run time. For example, if you have a figure class, it defines a draw method. And derived the circle and rectangle classes, in the derived class you override the draw method, you may also have a function that expects a parameter x, and can call $x->draw(). If you have polymorphism, which draw method is called depends on the type of object you pass to the function.
Polymorphism in interpreted languages like PHP (imagine a C++ compiler generating code like this, which method should you call? You also don’t know what type of object you have , well, that's not the point) is very easy and natural. So of course PHP supports polymorphism.
-------------------------------------------------- ---------
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);
//The draw method of Circle will be called
$board->niceDrawing($obj2);
//The draw method of Rectangle will be called Methods
?>
Object-oriented programming with PHP
Some "purists" may say that PHP is not a real For object-oriented languages, this is true. PHP is a hybrid language, you can use OOP or traditional procedural programming. However, for larger projects, you may want/need to use pure OOP to declare classes in PHP, and only use objects and classes in your project.
As projects get larger, it may be helpful to use OOP. OOP code is easy to maintain, easy to understand and reuse. These are the foundations of software engineering. Applying these concepts in web-based projects becomes the key to future website success.
Advanced OOP Technology in PHP
After looking at the basic OOP concepts, I can show you more advanced technology:
Serializing )
PHP does not support persistent objects. In OOP, a persistent object is an object that can maintain state and functionality among references in multiple applications. This means having 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 has a serialization method, which can be called through an object. The serialization method can return a string representation of the object. However, serialization only saves the member data of the object and not the methods.
In PHP4, if you serialize the object into the string $s, then release the object, and then deserialize the object into $obj, you can continue to use the object's methods! I don't recommend doing this because (a) there is no guarantee in the documentation that this behavior will still work in future versions. (b) This may lead to a misunderstanding when you save a serialized version to disk and exit the script. When you run this script later, you can't expect that when you deserialize an object, the object's methods will be there, because the string representation doesn't include methods at all.
In short, serialization in PHP is very useful for saving member variables of objects. (You can also serialize related arrays and arrays into a file).
Example:
--------------------------------------- --------------
$obj=new Classfoo();
$str=serialize($obj);
//Save $ str to disk
//A few months later
//Load str from disk
$obj2=unserialize($str)
?>-------------------------------------------------- ----
You restored the member data, but not the methods (according to the documentation). This results in the only way to access member variables (you have no other way!) by something like using $obj2->x, so don't try it at home.
There are some ways to solve this problem, I'm leaving them out because they are too bad for this concise article.
I would happily welcome fully serialized features in subsequent versions of PHP.
Methods to develop large PHP projects (4)
Use classes for data storage
A very good thing about PHP and OOP is that you can easily define a class to Operate something and call the corresponding class whenever you want to use it. Suppose you have an HTML form that allows the user to select a product by selecting the product ID number. There is product information in the database, and you want to display the product, its price, etc. You have different types of products, and the same action can mean different things to different products. For example, displaying a sound might mean playing it, but for other kinds of products it might mean displaying an image stored in a database. You can use OOP or PHP to reduce coding and improve quality:
Define a class for a product, define the methods it should have (eg: display), then define a class for each type of product, from After the product class comes out (SoundItem class, ViewableItem class, etc.), override the methods in the product class to 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, etc. fields)... Then In the processing script, you can retrieve the type value from the database and instantiate an object named type:
-------------------------- ------------
$obj=new $type();
$obj->action();
?>
This is a very good feature of PHP. You can call the display method or other methods of $obj without considering the type of object. Using this technique, you don't need to modify the script to add a new type of object, just a class to handle it.
This function is very powerful. Just define methods without considering the types of all objects, implement them in different classes in different methods, and then use them on any object in the main script. No if...else, no need for two programmers, just happiness.
Now you agree that programming is easy, maintenance is cheap, and reusability is true?
If you manage a group of programmers, assigning work is very simple. Each person may be responsible for a type of object and the class that handles it.
Internationalization can be achieved through this technology, just apply the corresponding class according to the language field selected by the user, etc.
Copy and Clone
When you create an object of $obj, you can copy the object by $obj2=$obj, and the new object is a copy of $obj ( not a reference), so it has the state of $obj at that time. Sometimes, you don't want to do this. You just want to generate a new object like the obj class. You can call the constructor of the class by using the new statement. This can also be achieved in PHP through serialization and a base class, but all other classes must be derived from the base class.
Enter the danger zone
When you serialize an object, you will get a string in some format, you can investigate if you are interested It, in it, has the name of the class in the string (great!), and you can take it out, like:
----------------- -----------------------
$herring=serialize($obj);
$vec=explode(':', $herring);
$nam=str_replace(""",'',$vec[2]);
?>
So let’s say you create a "Universe" class, and forces all classes to extend from universe. You can define a clone method in universe, 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 one An object of the Something class is the same as an object created by using the new method and calling the constructor. I don't know if this will work for you, but it's a good rule of thumb that the universe class knows the name of the derived class. Imagination is the only limit.