search
HomeBackend DevelopmentPHP TutorialPHP 高手之路(二)_php基础

二、编写漂亮的代码
  1.将后台程序与前端程序分开
  在编写PHP程序时,有些代码是用来处理一些事务,例如操作数据库、进行数学运算等,而另外的一些代码则只是事务处理的结果显示出来,例如一些使用echo语句将结果以HTML的格式显示在Web浏览器上的PHP代码以及那些直接嵌入PHP程序的HTML代码。首先我们应该清晰地区分这两种代码,把前者称为后台程序,把后者称为前端程序。
  因为PHP是一种嵌入式编程语言,也就是说,所有的PHP代码都可以嵌入到HTML代码之中,这为程序的编写带来了许多便利之处。但是,“物极必反”,如果在一段较长的程序中将PHP代码和HTML代码混合编写,这将使程序杂乱无章,不利于程序的维护和阅读。所以我们需要尽可能地将这些程序中混杂于HTML代码中的PHP代码移植出来,在专门的文件中将这些代码封装成函数,然后在HTML代码中使用include语句来包含这些文件,在适当的位置调用这些函数即可。
  这种做法一方面使HTML代码和PHP代码都简单易读,另一方面因为HTML代码需要不断更新,而这种分离的方法可以确保后台程序不会被破坏。
  同前端程序不同,后台程序更多追求的是稳定、结构化,极少更改,所以应该认真地设计和管理。其实,在设计台程序时,投入大量时间是值得的,“现在栽树,以后乘凉”,在以后的设计工作中将可以轻松地使用现在编写的后台程序。
  2.灵活使用包含文件
  正如前面所说的那样,后台程序应当安排在一系列的包含文件中。包含文件可以通过include语句在需要时动态装入,也可以在php.ini文件中通过使用auto_prepend_file指令预先自动装入。
  如果使用后一种方法的话,虽然取得了一劳永逸的好处,但是也有一些缺点值得我们注意。下面的一段代码向我们展示了解析一个庞大的包含文件需要一定的时间:
    require(timing.inc);
  ss_timing_start();
  include(test.inc);
  ss_timing_stop();
  echo
.ss_timing_current().

  ?>
  在上面的代码中,test.inc是一个1000行的包含文件,运行的结果显示,解析这个包含文件花费了0.6秒钟,对于一个大型网站来说,这个速度并不是可以忽略不记的。
  使用包含文件的另外一个缺点是:如果一个文件中的一个语句发生错误,将会使整个网站的PHP程序都无法运行。所以使用起来也及其小心。
  其实,对包含文件稍做处理,即可以使包含文件只在需要时进行解析。下面的代码使abc.inc文件只在程序需要时才作解析:
    if ( defined( __LIBA_INC) ) return;
  define( __LIBA_INC, 1 );
  /*
  * 代码...
  */
  ?>
  3.使用面向对象的编程方法
  PHP也是一种面向对象的语言,面向对象的编程方法是优秀的程序员们非常推崇的一种软件设计方法,在PHP编程中可以充分发挥面向对象语言的优势,对编程中的对象进行封装。在前面的代码中,我们使用了面向对象的方法,例如在管理数据库时,我们将query()函数封装进数据库类中,这极大地方便了代码的管理,增加了程序的可读性。
  三、追求程序速度,而不是编程的速度
  在网站建设中,程序运行速度和网页下载速度都是关系成败的重要因素。作为一名Web程序员,应该更加注意代码的运行速度。下面介绍的几种方法都在不同程度上提高了代码的运行速度。
  1.使用内嵌的HTML代码,而不是PHP的echo语句。
  因为PHP是一门嵌入式Web编程语言,可以将HTML代码和PHP代码相互嵌入。但是很多程序员担心在HTML代码中过多的使用""嵌入PHP代码会多次调用PHP解释器,从而降低了PHP代码的运行速度,所以宁愿使用PHP的echo语句来输出HTML代码,而不直接使用HTML代码。但事实却恰恰相反。每一个PHP页面只调用一次PHP解释器来解释所有的PHP代码,所以,只在需要时才嵌入PHP代码,而大多数的时候直接使用HTML代码输入结果,不但不会降低程序的运行速度,而且因为减少了对echo语句的解析,往往可以提高代码的运行速度。
  下面的一段代码证明了我们的结论。在这段代码中,我们使用了前面介绍的时间测试函数。

  

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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!