php autoload用法,php 方法autoload 和 spl_autoload_register 的用法

在开发大型项目的时候,引入文件是非常多的,

为了防止文件重名我们会定义命名空间,命名空间使用namespace定义。

为了代码的高度复用,我们会采用文件引入的形式,比如说使用  require、include 引入。

项目越来越大,那么使用的require 会越来越多,有没有一种办法可以自动引入类库呢?

应着这样的需求,__autoload  函数  和 spl_autoload_register 函数就出现了。

现在就来看看是如何引入的:

分两种情况:

1、spl_auload_register#init.php

namespace desgin\celue2;

class Init{

public static function _autoload($class){

$file=ROOT_PATH."/".str_replace("\\","/",$class).".php";

if(is_file($file)){

require_once $file;

}

}

}

#index.php

namespace desgin\celue2;

define("ROOT_PATH",dirname(dirname(dirname(__FILE__))));

//引入 init.php

include_once "init.php";

//自动引入加载类

spl_autoload_register('\desgin\celue2\Init::_autoload');

#\desgin\celue2\Init::_autoload     切记没有括号  和参数类

class Index{

protected $strategy;

public function view(){

$this->strateg->ad();

$this->strateg->love();

}

public function set(Strategy $strategy){

$this->strateg=$strategy;

}

}

$Index=new Index();

if(isset($_GET['t']) && $_GET['t']=="female"){

$Index->set(new Female());

}else{

$Index->set(new Man());

}

$Index->view();

2、__autoload//首先判断类是否存在,如果存在就引入.

function __autoload($class){

if(file_exists($class.".php")){

include_once $class.".php";

}

}

两种定义方式都是自动引入文件,那么两者有什么区别?

1、__autoload 在整个项目中只能定义一个函数方法

2、spl_autoload_register() 允许在同一个项目中定义多个方法,引入不同文件下的文件。

在现在这个项目中,经常会使用  composer 工具 拉取一些代码,都会自动引入自己的类库,这样就能显现出spl_autoload_register 的优势了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值