search
HomeBackend DevelopmentPHP TutorialPHP脚本的10个技巧(3)_php基础

包含文件
如果你目前着手的Web站点开发项目规模较大,那你对代码重用必定深有体会,比方说,不管是HTML还是PHP代码块,只要项目足够大,比如有1000个Web页,你即便是一年只修改一次包含版权信息的页脚也会让你痛不欲生。

而PHP可以通过一些函数帮助你重用代码,你要具体用到的函数依赖于你打算重用的内容。

主要的函数是:

* include() 和 include_once()
* require() 和require_once()

include()函数包含给定的文件,比如:

include('/home/me/myfile');

包含文件中的任何代码都将在include() 所在的代码页的变量范围之内执行。你可以包含服务器上的静态文件或者包含在其他服务器上的目标文件,方法是组合使用include()和fopen()。

include_once()函数和include()函数功能类似,只是该函数会检查被包含文件内的代码是否已经被目前的脚本所包含过。如果代码已经被脚本所包含,该函数就不再包含相应的文件了。

require()函数用给定文件的内容取代自身。这一替换过程发生在PHP引擎编译你的代码而不是执行代码阶段,这可和include()不一样,后者首先被计算再加到文挡中。require()函数多用于静态元素,而include()函数则主要用于动态元素。和include_once()类似,require_once()函数会检查给定代码是否早已经插入到了文挡内,如果这样,给定代码就不会被再次插入文档。

我建议你最好对诸如版权、静态文本和其他不含变量的元素这类信息采用require函数,那些依赖其他脚本来实现自己内容的元素也最好采用require函数,例如:


Something

[a lot of content]


// insert copyright
require('/home/me/mycopyright');
?>




另一方面,我经常用include()函数把函数库或类似的内容放到脚本之外:


// get my function library
include('/home/me/myfunctions');

// do PHP things with my functions ?>


Something

[a lot of content]



你肯定会问:“那么,被included或者被required的文件都来自哪里呢?”答案很简单:“你的系统。”不过,有时,有些代码会包含了诸如带有用户名和密码的数据库连接函数之类的安全信息,在这样的情况下,显而易见,你肯定不希望这些东西也成为文档的一部分弄得全世界都知道。

你可以把包含文件(included或者required)放在系统的任何地方,只要用户所能用到的PHP可以访问这些文件即可。你还可以给这些文件以任何你希望给出的文件扩展名,或者不设扩展名。

使用include()和require()函数可以让Web站点上普遍存在或者经常变动的元素变得更加容易处理。


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 Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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.

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use