search
HomeBackend DevelopmentPHP TutorialComparison of the advantages and disadvantages of PHP object-oriented and PHP process-oriented_PHP Tutorial

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>
<li class=""><span>print"Hello,world.";  </span></li>
<li class="alt">
<span></span><span class="tag"><strong><font color="#006699">?></font></strong></span><span> </span>
</li>
</ol>
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>
<li class=""><span>classhelloWorld{  </span></li>
<li class="alt"><span>functionmyPrint(){  </span></li>
<li class=""><span>print"Hello,world.";  </span></li>
<li class="alt"><span>}  </span></li>
<li class=""><span>}  </span></li>
<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>
</li>
<li class="">
<span>$myHelloWorld-</span><span class="tag"><strong><font color="#006699">></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>

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
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怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool