Home Backend Development PHP Tutorial Comparison of the advantages and disadvantages of PHP object-oriented and PHP process-oriented_PHP Tutorial

Comparison of the advantages and disadvantages of PHP object-oriented and PHP process-oriented_PHP Tutorial

Jul 15, 2016 pm 01:28 PM
php and Advantages and Disadvantages use and exist object of process For

Object-oriented and process-oriented. In many programming languages, only one of the two can be used for programming, but the PHP language is different from other programming languages, that is, we can freely choose or use If you are new to PHP, writing code in PHP's process-oriented style is probably your only choice. But if you frequent PHP forums and newsgroups, you should see articles about "objects". You may also have seen tutorials on how to write object-oriented PHP code. Or you may have downloaded some ready-made class libraries and tried to instantiate objects and use class methods in them - although you may not really understand why these classes work, or why you need to use PHP object-oriented methods to implement them. Function.

Should we use the "object-oriented" style or the "process-oriented" style? Both sides have supporters. Comments like "the object is inefficient" or "the object is great" are also heard from time to time. This article does not attempt to easily determine which of the two methods has the absolute advantage, but rather to find out the advantages and disadvantages of each method.

The following is a code example of PHP process-oriented style:

<ol class="dp-xml"><li class="alt">
<span><strong><font color="#006699"><span class="tag"><?</SPAN><SPAN class=tag-name>php</SPAN></FONT></STRONG><SPAN> </SPAN></SPAN><LI class=""><SPAN>print"Hello,world.";  </SPAN><LI class=alt><SPAN></SPAN><SPAN class=tag><STRONG><FONT color=#006699>?></span></font></strong></span><span> </span>
</li></ol>
Copy after login
The following is a code example of PHP object-oriented style:

<ol class="dp-xml">
<li class="alt">
<span><strong><font color="#006699"><span class="tag"><?</SPAN><SPAN class=tag-name>php</SPAN></FONT></STRONG><SPAN> </SPAN></SPAN><LI class=""><SPAN>classhelloWorld{  </SPAN><LI class=alt><SPAN>functionmyPrint(){  </SPAN><LI class=""><SPAN>print"Hello,world.";  </SPAN><LI class=alt><SPAN>}  </SPAN><LI class=""><SPAN>}  </SPAN><LI class=alt><SPAN>$</SPAN><SPAN class=attribute><FONT color=#ff0000>myHelloWorld</FONT></SPAN><SPAN>=</SPAN><SPAN class=attribute-value><FONT color=#0000ff>newhelloWorld</FONT></SPAN><SPAN>();  </SPAN></SPAN><LI class=""><SPAN>$myHelloWorld-</SPAN><SPAN class=tag><STRONG><FONT color=#006699>></span></font></strong></span><span>myPrint();  </span>
</li>
<li class="alt">
<span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span>
</li>
</ol>
Copy after login

If you want to know some basic knowledge of "object-oriented", please use Google search, on the Internet There are so many wonderful articles.

Who writes code like this?

To understand why this topic has become the trigger of wars of words on the forum, let’s look at some of the more extreme examples from each camp. Let’s look at “process fanaticism” and “object fanaticism.” See if their ideas sound familiar.

Process Fanatics

Process Fanatics was once criticized by computer teachers in class because this method did not use a more abstract implementation. And supporting PHP's process-oriented point of view "it can work!" does not improve its programming level and grade. After graduation they may find a job writing drivers, file systems or other low-level programming where their attention is focused on speed and code refinement.

An extreme example of "process fanaticism" is resistance to objects and abstraction. They are always thinking about how to make the program run faster, and they don't care whether others can read their code. They often view programming as a competition rather than a team activity. Besides PHP, their favorite programming languages ​​are C and assembly. In the PHP world, they may develop PECL modules and contribute efficient code.

Object fanatics

Object fanatics are passionate about writing code in PHP object-oriented style at all times. They have not really considered whether using this method will affect the execution efficiency of the program. Sometimes it feels like they enjoy abstract design concepts more than realistic code. They are usually project managers or document writers.

Object fanatics point out that without abstract design methods we would still be programming with 0s and 1s. They like to use pseudocode to describe problems. An extreme example is the object fanatic who still uses objects even though he or she knows that efficiency is sometimes sacrificed. Besides PHP, their favorite languages ​​are Java and Smalltalk. In the PHP world, they might develop PEAR modules, contributing very well-documented, easy-to-maintain code.

Don’t be extreme and sarcastic

Do you know why forums are always full of prejudice? Your experience and attitude towards new things may be the reason. As programmers, we need to always be aware of these biases and be open to learning new things.

What are your coding tendencies?

Consider what preferences or tendencies you have when writing PHP code. Often these preferences are rather subtle. Sometimes you may have the same preferences in every project. I personally prefer "elegant", but I don't want to define what constitutes "elegant" code here, that should appear in another article. However, theorized preferences are not necessarily appropriate for actual projects—rather, they are often biases.

Theoretical tendency

•Provide a complete solution with the minimum number of lines of code

•Consider the problem at the problem level

This sounds like It seems to look good. But how to measure "the fewest lines of code"? Should code comments be included? Should we concatenate each line and only use semicolons to distinguish them? What about braces? Obviously this idea is wrong.

Explain again what "problem level" is. Does this mean that every concept in our solution needs to have a class? Or do you need to keep each part of the problem in a separate file and build a complex file tree to correspond to the real-life problem? That's the idea - have a file or class for each idea!

Obviously these generalizations become ridiculous when taken to the extreme. But there is more subtle proof in reality. How often does a programmer insert a line of complex, powerful but uncommented code while working in a team? This is undoubtedly very frustrating for the people who take over the maintenance of these codes. On the contrary, do your bureaucratic and self-righteous superior programmers often go on a "rampage" to establish interfaces and classes? And those interfaces and classes not only limit the programmers responsible for implementation, but also limit efficiency and flexibility. This leads to confusion when customers ask for extensions. These are subtle proofs of each of the above tendencies.

Practical tendency

When starting a project, you must first seek the actual coding purpose and direction. What are the goals of this project? Here are the possible answers.

• Fast to develop, fast to release

• Run as fast as possible

• Easy to maintain, improve and extend

• Release an API

The first and second directions tend to use the procedural style, while the last two tend to use the PHP object-oriented style.

When is a certain approach more effective?

Now let’s try to evaluate the real-world advantages of each approach.

PHP procedural case

A basic argument about the advantages of PHP's procedural programming is: PHP is an interpreted language - which means that, unlike Like other languages, it is not compiled into an executable package, but is interpreted and executed immediately. It is a scripting language and is stored in text files (except if the Zend compilation tool is used).

Another reason against using object-oriented coding in PHP4 and lower versions is that the functionality of objects was not well designed in earlier versions of PHP. As Rasmus once said: "It was an afterthought." This means that in PHP4 and earlier, object efficiency was an issue. But after PHP5 comes out, this situation will change.

The following two most popular PHP programs - OsCommerce and PhpMyAdmin. mainly use process-oriented coding. They are fast to build and fast to run. Both naturally take the approach of embedding HTML.

OsCommerce

OsCommerce actually uses many objects, but most of the functions are implemented through "processes". I once hacked OsCommerce to add some custom features that were very useful to customers. This process is quite troublesome, because many process codes in OsCommerce do not use a templated system and are designed in multi-language versions, so it takes a certain amount of time to get started. But it works, and in fact it already works very well on numerous e-commerce sites. OsCommerce also provides a forum and a development framework for developing modules and plug-ins. Therefore, there are now many useful functional modules provided by other developers.

PhpMyAdmin

PhpMyAdmin directly uses only one class: MimerSQLValidator class, which depends on Mail_Mime, Net_DIME and SOAP in the PEAR package. This may be due to the convenience of development: using ready-made code that can achieve the purpose. Beyond that, everything is procedural and HTML and PHP code are mixed together.

PhpMyAdmin is a tool that I use almost every day for less complex processing of a small number of data tables. Sometimes I even encourage my clients to use it as a back-end management tool (of course I limit their permissions). PhpMyAdmin performs very well and is very fast. Sometimes I want to extend PhpMyAdmin as a back-end management tool in some projects, and use some of its new features such as data query statement bookmarks to easily display it to my customers and editors. With each new version, PhpMyAdmin becomes more and more useful and powerful. Software Development Network

Summary of PHP process-oriented

The above two programs using process-oriented style have very good documentation and code comments. The development framework provided by OsCommerce can increase maintainability and scalability. However, neither provides an API and cannot extend the program to other systems.

If you want to integrate OsCommerce into a billing program, it will take a lot of time and effort, like extending PhpMyAdmin into a backend management tool for customers. However, judging from the purpose of their design, they do perform very well in their respective fields.

PHP Object-Oriented Case

The views of those who support the object-oriented style focus on extensibility and encapsulation. Simply writing code in an object-oriented way won't document your code, but it will encourage you to document it. And, for ease of extensibility, you might write an API. PHP5 promises to make object-oriented programming more enjoyable. I jokingly call it the "Java 2" version of PHP because it integrates many features in Java, like interfaces, object-oriented models, try-catch statements, etc. But even in PHP4, which has weak object-oriented support, there are still many excellent object-oriented applications.

Smarty

Smarty is used to build template-based sites with complex forms. Recently, I wrote an online exam system that can be completely "skinned" - the appearance, interface and style of the entire site can be completely changed without changing any underlying code or functions. In order to make it easy for designers to design new interfaces, I designed a custom tag library as an extension of the Smarty tag library. It can be simply inserted like this:

[navigationhorizontalseparatedby"|"]

Having separated navigation at the top of a page. Because Smarty already provides a very powerful mechanism to represent the data contained in variables, this is a simple process of mapping more complex Smarty tags to skin tags.

Because Smarty is encapsulated as a class and its methods are well documented, the process of using templates becomes incredibly easy to extend. At the same time, Smarty also provides a layer of protection for PHP environment variables by forcing you to explicitly pass only the variables you want to use to Smarty template methods. This approach helps establish a safe, reliable working relationship between Smarty template designers and programmers.

FPDF

FPDF is a very excellent tool. If you are confused by the changing API of pdflib, or are unwilling to pay for a commercial solution; or are unable to use extension modules due to the limitations of shared hosting - please consider using this free, pure PHP built PDF generation tool.

This class is well documented, including many good examples of how to lay out text and images in PDFs. On the same online learning site mentioned above I use FPDF to generate PDF files dynamically, using truetype fonts and images with 300dpi accuracy. Instantiating the FPDF class in PHP and doing PDF manipulation doesn't take much extra time, since the PDF itself can take a few minutes to download. In fact, dynamically generating and delivering a PDF takes no more time than delivering a static PDF file over a slow network connection. This is all relative. And, since FPDF is class-based, it can be extended. In fact, some class methods exist but are not fully implemented yet, serving merely as a framework to guide you in building your own content (such as custom header and footer elements) in subclasses.

PHP Object-oriented Summary

Both Smarty and FPDF provide well-documented APIs to extend the main class. This illustrates the necessity of organizing methods and data within a class - sometimes the same functionality can be accomplished using functions and global variables, but this is not easy to extend. Moreover, using objects is very helpful for tracking and maintaining the style of PDF or HTML documents. You can publish the same data in different formats. Smarty and FPDF are both excellent examples of using objects to build flexible and practical class libraries.

Why are both methods necessary?

Back to our passionate programmers, we start by praising them:

• We appreciate the practicality and extensibility of Smarty and FPDF

• We appreciate the speed and good performance of osCommerce and phpMyAdmin Performance

This appreciation also includes some basic development of PHP. Both PECL and PEAR have received a lot of praise and criticism. I think these two projects provide good examples of clarifying the difference between procedural and object-oriented programming in PHP.

PECl provides an extension library for PHP, developed in C and process-oriented manner, focusing on speed and simplicity. Typically, these are ports from already existing LGPL software, where many interesting features have been added to PHP. After all, PHP is written in C.

PEAR has contributed many interesting classes such as creating Excel tables or changing DNS records. Using the PEAR class library can save you a lot of time, and even allows you to develop without being familiar with PHP - "I don't understand it but it works!".

Summary

I hope this article can deepen your understanding of the two programming methods of PHP object-oriented and PHP process-oriented, and more importantly - encourage you to work on more specific details Explore. I hope you will have your own ideas, test your project development tendencies in actual development, summarize more practical cases, and do not hesitate to write some comments on this article.

In short, each method has its advantages. It is better to leave and write some actual code than to get entangled in the debate!


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/446406.htmlTechArticleObject-oriented and process-oriented. In many programming languages, only one of the two can be used for programming, but the PHP language What is different from other programming languages ​​is that we can choose freely...
Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 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.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 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

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.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles