PHP面向对象——Final关键字 类的自动加载

 

1.Final关键字

 

含义:最终的,最后的

作用

1.如果父类中的方法被声明为 final,则子类无法覆盖该方法。

如果一个类被声明为 final,则不能被继承。

2.属性不能被定义为 final,只有类和方法才能被定义为 final。

用法:直接在类或者方法前加final关键字。

---------------------------------------------------------------------------

2.类的自动加载

 

含义:

1.解决代码重复,把重复的代码写在一个文件夹中,让其他PHP文件调用自动加载。

 

2.解决PHP文件过多 include等引入PHP过于庞大造成负担。

实现函数:

spl_autoload_register() 函数:可以注册任意数量的自动加载器。

__autoload():尝试加载未定义的类 也能自动加载类和接口(不推荐,可能被弃用)。(注意:处理大量程序时使程序变得臃肿,无法实现,代码变复杂,给未来的系统维护和系统效率带来很大的负面影响)

注意:自动加载不可用于 PHP 的 CLI 交互模式

 

php加载文件方式:
1、include,include_once,requice,requice_one常规加载
2、__autoload()
3、spl_autoload_register()

 

__autoload()自动加载

<?php 
function __autoload( $class ){ 
   $file = $class . '.php' ;//拼接路径 
   if ( is_file ( $file )) { //判断$file是否存在
     require_once ( $file ); //从$file路径导入一次
  
$a = new A();
注意:由于__autoload()是个函数,只能存在一次。
-----------------------------------------------------------------------------
spl_autoload_register()自动加载
 
spl_autoload_register()  它实际上创建了 autoload 函数的队列,按定义时的顺序逐个执行。相比之下, __autoload() 只可以定义一次。
<?php 
function loader( $class ){ 
   $file = $class . '.php'
   if ( is_file ( $file )) { 
     require_once ( $file ); 
  
spl_autoload_register( 'loader' ); 
$a = new A();
 
直接使用匿名函数:
<?php 
  
spl_autoload_register( function ( $file ){
   $file = $class . '.php'
   if ( is_file ( $file )) { 
     require_once ( $file ); 
   }
}); 
$a = new A();
 

这样子也是可以正常运行的,这时候php在寻找类的时候就没有调用__autoload而是调用我们自己定义的函数loader了。同样的道理,下面这种写法也是可以的:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php 
class Loader { 
   public static function loadClass( $class ){ 
     $file = $class . '.php'
     if ( is_file ( $file )) { 
       require_once ( $file ); 
    
  
spl_autoload_register( array ( 'Loader' , 'loadClass' ));
//spl_autoload_register(array(__CLASS__, 'loadClass'));
//spl_autoload_register(array($this, 'loadClass'));
$a = new A();

 

 

 

 

转载于:https://www.cnblogs.com/jianjianbeibei/p/7226654.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值