传统上,在PHP里,当我们要用到一个class文件的时候,我们都得在文档头部require或者include一下:本文主要和大家介绍PHP文件的自动加载(autoloading)相关知识点以及详细用法,有这方面需要的朋友参考下吧,希望能到大家。
<?php require_once('../includes/functions.php'); require_once('../includes/database.php'); require_once('../includes/user.php'); ...
但是一旦要调用的文档多了,就得每次都写一行,瞅着也不美观,有什么办法能让PHP文档自动加载呢?
<?php function __autoload($class_name) { require "./{$class_name}.php"; }
对,可以使用PHP的魔法函数__autoload(),上面的示例就是自动加载当前目录下的PHP文件。当然,实际当中,我们更可能会这么来使用:
<?php function __autoload($class_name) { $name = strtolower($class_name); $path = "../includes/{$name}.php"; if(file_exists($path)){ require_once($path); }else{ die("the file {$class_name} could not be found"); } }
也即是做了一定的文件名大小写处理,然后在require之前检查文件是否存在,不存在的话显示自定义的信息。
类似用法经常在私人项目,或者说是单一项目的框架中见到,为什么呢?因为你只能定义一个__autoload function,在多人开发中,做不到不同的developer使用不同的自定义的autoloader,除非大家都提前说好了,都使用一个__autoload,涉及到改动了就进行版本同步,这很麻烦。
也主要是因为此,有个好消息,就是这个__autoload函数马上要在7.2版本的PHP中弃用了。
Warning This feature has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged.
那么取而代之的是一个叫spl_autoload_register()的东东,它的好处是可以自定义多个autoloader.
//使用匿名函数来autoload spl_autoload_register(function($class_name){ require_once('...'); });
//使用一个全局函数 function Custom() { require_once('...'); } spl_autoload_register('Custom');
//使用一个class当中的static方法 class MyCustomAutoloader { static public function myLoader($class_name) { require_once('...'); } } //传array进来,第一个是class名,第二个是方法名 spl_autoload_register(['MyCustomAutoloader','myLoader']);
//甚至也可以用在实例化的object上 class MyCustomAutoloader { public function myLoader($class_name) { } } $object = new MyCustomAutoloader; spl_autoload_register([$object,'myLoader']);
值得一提的是,使用autoload,无论是__autoload(),还是spl_autoload_register(),相比于require或include,好处就是autoload机制是lazy loading,也即是并不是你一运行就给你调用所有的那些文件,而是只有你用到了哪个,比如说new了哪个文件以后,才会通过autoload机制去加载相应文件。
当然,laravel包括各个package里也是经常用到spl_autoload_register,比如这里:
/** * Prepend the load method to the auto-loader stack. * * @return void */ protected function prependToLoaderStack() { spl_autoload_register([$this, 'load'], true, true); }
相关推荐:
Zend Framework教程之Autoloading用法详解
PHP的PSR-0标准利用namespace来做autoloading
Zend Framework教程之Autoloading用法详解
以上是PHP文件的自动加载autoloading详解的详细内容。更多信息请关注PHP中文网其他相关文章!

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

你应该关心DependencyInjection(DI),因为它能让你的代码更清晰、更易维护。1)DI通过解耦类,使其更模块化,2)提高了测试的便捷性和代码的灵活性,3)使用DI容器可以管理复杂的依赖关系,但要注意性能影响和循环依赖问题,4)最佳实践是依赖于抽象接口,实现松散耦合。

是的,优化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)优化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,并避免使用

theKeyStrategiestosiminificallyBoostphpapplicationPermenCeare:1)useOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)优化AtabaseInteractionswithPreparedStateTemtStatementStatementSandProperIndexing,3)配置

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增强codemodocultion,可验证性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

选择DependencyInjection(DI)用于大型应用,ServiceLocator适合小型项目或原型。1)DI通过构造函数注入依赖,提高代码的测试性和模块化。2)ServiceLocator通过中心注册获取服务,方便但可能导致代码耦合度增加。

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)启用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替换loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

phpemailvalidation invoLvesthreesteps:1)格式化进行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3汉化版
中文版,非常好用

Dreamweaver CS6
视觉化网页开发工具

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)