Home >Backend Development >PHP Tutorial >Methods to develop large-scale PHP projects_PHP tutorial
Methods for developing large-scale PHP projects
Object-oriented programming (OOP, Object Oriented Programming) in PHP is introduced here. You'll be shown how to reduce coding and improve quality by using some OOP concepts and PHP techniques. 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
is encapsulated through classes in PHP:
Code:
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, For example getValueOfArea()
$this->x=$v;
}
function getX() {
return $this->x;
}
}
?>
Of course you can define it according to your own preferences, but it is better 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 a 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 x of the object (not 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.
Code:
class Another extends Something {
var $y;
function setY($v) {
$this-> ;y=$v;
}
function getY() {
return $this->y;
}
}
?>
The object of "Another" class now has all the data members and methods of the parent class (Something), and also adds its own data members and methods.
You can use the
code:
$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, which is called when you create an object of the class, for example:
Code:
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 by:
$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 a default parameter to X. The parameters are assigned from left to right. If the parameters passed in are less than the required parameters, the other 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, you must do it in the derived class. Explicit call in constructor. This can be done because all methods of the parent class are available in the derived class.
Code:
function Another() {
$this->y=5;
$this->Something();
//Explicitly calling the base class constructor
}
?>
A good mechanism for OOP 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 a base class and add a "die" call after its constructor, so that you can ensure that the base class is Non-instantiable, now adds a "die" statement 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.
Overloading (unlike overriding) 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 through different methods (passing different numbers of arguments). The trick to implement it in PHP
is:
Code:
class Myclass {
function Myclass() {
$name= "Myclass".func_num_args();
$this->$name();
//Note that $this->name() is generally wrong, but here $name is the one that will be called Method name
}
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, which can decide which object method to call based on the passed object parameters at runtime. 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.
Code:
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
?>
Object-oriented programming with PHP
Some "purists" may say that PHP is not a true object-oriented language, and 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 in PHP to declare classes, 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 technologies in PHP
After looking at the basic OOP concepts, I can show you more advanced technologies:
Serializing (Serializing)
PHP does not Support for 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 to load the object later. This is the so-called serialization mechanism. PHP has a serialization method that can be called on an object, and 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:
Code:
$obj=new Classfoo();
$str=serialize($obj);
//A few months later
//Load str from disk
$obj2=unserialize($str)
?>
You restore Member data is included, but methods are not included (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.
Use classes for data storage
One very nice thing about PHP and OOP is that you can easily define a class to operate something and use it whenever you want The corresponding class can be called. 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)... and then process the script , you can retrieve the type value from the database and instantiate an object named type:
Code:
$obj=new $ type();
$obj->action();
?>
This is a very good feature of PHP, you don’t need to consider objects Type, call the display method or other methods of $obj. 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, without if. ..else, there is no need for two programmers, only 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 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, and so on.
Copy and Clone
When you create an object of $obj, you can copy the object by $obj2=$obj. 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.
Entering the danger zone
When you serialize an object, you will get a string in some format. If you are interested, you can investigate it. Among them, there are classes in the string name (so great!), you can take it out, like:
Code:
$herring=serialize($obj);
$vec=explode(':',$herring);
$nam=str_replace(""",'',$vec[2]);
?>
So assuming you create a "Universe" class and force all classes to extend from universe, you can define a clone method in universe, as follows:
Code:
class Universe {
function clone() {
$herring=serialize($this);
$vec=explode(':',$herring);
$nam=str_replace(""",'',$vec[2]);
$ret=new $nam;
return $ret;
}
}
//Then
$obj=new Something();
//Expand from Universe
$other=$obj->clone();
?>
What you get is a new object of the Something class, which is the same as the 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. (Source: Feng Shan)