這篇文章主要介紹了PHP SPL標準庫中的常用函數介紹,本文著重講解了spl_autoload_extensions()、spl_autoload_register()、spl_autoload()三個函數,需要的朋友可以參考下
PHP SPL標準庫中提供了一些函數用來處理如自動加載、迭代器處理等。
spl_autoload_extensions()添加spl_autoload()可加載的文件擴展名
spl_autoload_register()注冊函數到SPL __autoload函數棧中。
代碼如下:
- /*test1.php*/
- <?php
- class Test1
- {
- }
- /*test2.lib.php*/
- <?php
- class Test2
- {
- }
- /*test.php*/
- <?php
- //設置可加載類的文件擴展名
- spl_autoload_extensions(".php,.inc.php,.class.php,.lib.php");
- //設置include_path,autoload會在這些path中去尋找類文件,可通過PATH_SEPARATOR添加多個path
- set_include_path(get_include_path().PATH_SEPARATOR.'libs/');
- //不提供參數,默認實現函數是spl_autoload()
- spl_autoload_register();
$test1 = new Test1();
$test2 = new Test2();
spl_autoload()它是__autoload()的默認實現,它會去include_path中加載文件(.php/.inc),代碼如下:
- /*test1.php*/
- <?php
- class Test1
- {
- }
- /*test.php*/
- <?php
- set_include_path(get_include_path().PATH_SEPARATOR.'libs/');
- spl_autoload('test1');
- $test1 = new Test1();
spl_autoload_call()調用所有spl_autoload_register注冊函數來加載文件,代碼如下:
- /*test1.php*/
- <?php
- class Test
- {
- public function getFilename()
- {
- echo 'test1.php';
- }
- }
- /*test2.lib.php*/
- <?php
- class Test
- {
- public function getFilename()
- {
- echo 'test2.lib.php';
- }
- }
- /*test.php*/
- <?php
- function loader($classname)
- {
- if($classname == 'Test1') {
- require __DIR__ . '/test1.php';
- }
- if($classname == 'Test2') {
- require __DIR__ . '/test2.lib.php';
- }
- }
- spl_autoload_register('loader');
- spl_autoload_call('Test2');
- $test = new Test();
- $test->getFilename(); //test2.lib.php
其它SPL 函數介紹:
class_implements — 返回指定的類實現的所有接口。
class_parents — 返回指定類的父類。
class_uses — Return the traits used by the given class
iterator_apply — 為迭代器中每個元素調用一個用戶自定義函數
iterator_count — 計算迭代器中元素的個數
iterator_to_array — 將迭代器中的元素拷貝到數組
spl_autoload_functions — 返回所有已注冊的__autoload()函數
spl_autoload_unregister — 注銷已注冊的__autoload()函數
spl_classes — 返回所有可用的SPL類
spl_object_hash — 返回指定對象的hash id
如iterator相關函數使用:
- $iterator = new ArrayIterator (array( 'recipe' => 'pancakes' , 'egg' , 'milk' , 'flour' ));
- print_r(iterator_to_array($iterator)); //將迭代器元素轉化為數組
- echo iterator_count($iterator); //計算迭代器元素的個數
- print_r(iterator_apply($iterator, 'print_item', array($iterator)));//為迭代器每個元素
調用自定義函數
- function print_item(Iterator $iterator)
- {
- echo strtoupper ( $iterator -> current ()) . "/n" ;
- return TRUE ;
- }
新聞熱點
疑難解答