天天看點

php函數spl_autoload_register

緣由:

composer自動引入

定義:

首先spl_autoload_register的官方定義:注冊給定的函數作為 __autoload 的實作。

可以了解為替代_autoload函數的方案;

函數的使用:

關于spl_autoload_register的使用如下:

檔案1:ClassTest.php

<?php
Class classTest
{
	public function go()
	{
		echo 'success';
	}
}
           

檔案2:index.php

使用__autoload函數

<?php
funciton __autoload($class)
{
	$file = $class.'.php';
	require_one($file);
}

$obj = new ClassTest();
$obj->go();
           

執行index.php檔案,

得到結果 字元串success,

php在加載為定義的類的時候會觸發_autoload函數;

檔案3: index.php

<?php

function loadprint($class) {
	$file = $class.'.php';
	require_once ($file);
}
spl_autoload_register('loadprint');
$obj = new classTest();
$obj->go();
           

執行index.php檔案,

得到結果: 字元串success,

我們自定義了函數作為_autoload的實作,與autolod實作相同的功能;

那麼!

__autoload與spl_autoload_register功能一樣,為什麼不隻存在一個呢。

檢視官方文檔有這樣的解釋:

盡管 __autoload() 函數也能自動加載類和接口,但更建議使用 spl_autoload_register() 函數。 spl_autoload_register() 提供了一種更加靈活的方式來實作類的自動加載(同一個應用中,可以支援任意數量的加載器,比如第三方庫中的)。是以,不再建議使用 __autoload() 函數,在以後的版本中它可能被棄用。

同時:

請檢視以下例子:

檔案1:index.php

spl_autoload_register('loadprint');

function __autoload($class) {
	$file = 'classTest.php';
	require_once ($file);
}

function loadprint($class) {
	$file = 'classTest2.php';
	require_once ($file);
}

$obj = new classTest();
$obj->go();
           

檔案2:ClassTest.php

<?php
class classTest
{
	public function go()
	{
		echo 'success1';
	}
}
           

檔案3:ClassTest.php

<?php
class classTest
{
	public function go()
	{
		echo 'success2';
	}
}
           

執行index.php

結果:success2。

這部分内容涉及到了php的生命周期,

spl_autoload_register涉及到注冊函數隊列(php生命周期運作中會對函數的系統資料庫進行檢查),如果你代碼中既含有__autoload函數,又含有spl_autoload_register函數,則spl_autoload_register會取代__autoload。

spl_autoload_register更加靈活的實作了自動加載,同時在composer自動引入中也用到了大量的spl_autoload_register函數來實作,其實自動加載的最終原理還是require_one來實作。