__aotoload和spl_autoload_register区别以及用法

官方定义:
__autoload 尝试加载未定义的类 (函数已自 PHP 7.2.0 起被废弃,并自 PHP 8.0.0 起被移除)
spl_autoload_register 注册给定的函数作为 __autoload 的实现 (新版本的还是要用这个函数)

__aotoload 这是一个自动加载函数,在PHP5中,当我们实例化一个未定义的类时,就会触发此函数。看下面的一
个简单例子:

index.php:

<?php
	Class Index{
		public function CheckIndex()
		{
			echo 'hello world';die;
		}
	}

main.php

<?php
function __autoload($ClassName) {
	$file = $ClassName.'.php';
	if(is_file($file)) {
		include_once($file);
	} else { // 找不到就抛出错误异常
	
	}
}

$Obj =  new Index();
$Obj->CheckIndex();

运行 main.php 就会输出hello world 在main.php中由于没有包含index.php 所以出发了自动加载的函数__autoload() 参数$ClassName的值就是类名index,这时判断类名存在不存在 如果存在就包含进来 这种方式一般都用在面向对象中 可以避免书写过多的引用文件。

来看下 spl_autoload_register 的简单实例:

<?
function autoload( $ClassName) {
 $file = $class . '.php';
 if (is_file($file)) {
 	require_once($file);
 }
}
spl_autoload_register( 'autoload' );
$obj = new Index();
$obj->CheckIndex();

将spl_autoload_register换成autoload函数,但是autoload 不会像__autoload 一样自动触发,这时候spl_aotoload_register就起了作用 它告诉php碰到了没有定义的类 然后就执行了autoload方法
详情参见:PHP官方手册 spl_aotoload_register(); __autoload();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值