php入口文件的作用
php入口文件能够完成主动加载性能。
解析PHP入口文件的主动加载性能
php的主动加载:
正在php5之前,咱们要用某个类或类的办法,那必需include或许require,之后能力应用,每一次用一个类,都需求写一条include,费事
php作者想简略点,最佳能援用一个类时,假如以后不include出去,零碎能主动去找到该类,主动引进~
于是:__autoload()函数应运而生。
通常放正在使用顺序入口类外面,比方discuz中,放正在class_core.php中。
保举:《PHP教程》
先讲通俗的例子:
第一种状况:文件A.php中内容以下
<?php class A{ public function __construct(){ echo 'fff'; } } ?>
文件C.php 中内容以下:
<?php function __autoload($class) { $file = $class . '.php'; if (is_file($file)) { require_once($file); } } $a = new A(); //这边会主动挪用__autoload,引入A.php文件 ?>
第二种状况:有时我心愿能自界说autoload,而且心愿起一个更酷的名字loader,则C.php改成以下:
<?php function loader($class) { $file = $class . '.php'; if (is_file($file)) { require_once($file); } } spl_autoload_register('loader'); //注册一个主动加载办法,笼罩原本的__autoload $a = new A(); ?>
第三种状况:我心愿矮小上一点,用一个类来治理主动加载
<?php class Loader { public static function loadClass($class) { $file = $class . '.php'; if (is_file($file)) { require_once($file); } } } spl_autoload_register(array('Loader', 'loadClass')); $a = new A(); ?>
以后为最好方式。
通常咱们将spl_autoload_register(*)放正在入口剧本,即一开端就援用出去。比方上面discuz的做法。
if(function_exist('spl_autoload_register')){ spl_autoload_register(array('core','autoload')); //假如是php5以上,存正在注册函数,则注册本人写的core类中的autoload为主动加载函数 }else{ function __autoload($class){ //假如没有是,则重写php原生函数__autoload函数,让其挪用本人的core中函数。 return core::autoload($class); } }
这段扔正在入口文件最后面,天然是极好的~
以上就是php入口文件的作用的具体内容,更多请存眷资源魔其它相干文章!
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
抱歉,评论功能暂时关闭!