search
HomeBackend DevelopmentPHP TutorialMethods to develop large-scale PHP projects_PHP tutorial

Methods to develop large-scale PHP projects_PHP tutorial

Jul 21, 2016 pm 04:09 PM
oopphpexistLargeobjectdevelopmethodPurposeprogrammingFor


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)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314509.htmlTechArticleHow to develop large-scale PHP projects Here is an introduction to object-oriented programming (OOP, Object Oriented Programming) in PHP. Will show you how to use some OOP concepts and PHP techniques to...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment