PHP SPL標準庫中的常用函數(shù)介紹
PHP SPL標準庫中提供了一些函數(shù)用來處理如自動加載、迭代器處理等。
spl_autoload_extensions()添加spl_autoload()可加載的文件擴展名
spl_autoload_register()注冊函數(shù)到SPL __autoload函數(shù)棧中。
/*test1.php*/
<?php
class Test1
{
}
/*test2.lib.php*/
<?php
class Test2
{
}
/*test.php*/
<?php
//設(shè)置可加載類的文件擴展名
spl_autoload_extensions(".php,.inc.php,.class.php,.lib.php");
//設(shè)置include_path,autoload會在這些path中去尋找類文件,可通過PATH_SEPARATOR添加多個path
set_include_path(get_include_path().PATH_SEPARATOR.'libs/');
//不提供參數(shù),默認實現(xiàn)函數(shù)是spl_autoload()
spl_autoload_register();
$test1 = new Test1();
$test2 = new Test2();
spl_autoload()它是__autoload()的默認實現(xiàn),它會去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()調(diào)用所有spl_autoload_register注冊函數(shù)來加載文件
/*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 函數(shù)介紹:
class_implements — 返回指定的類實現(xiàn)的所有接口。
class_parents — 返回指定類的父類。
class_uses — Return the traits used by the given class
iterator_apply — 為迭代器中每個元素調(diào)用一個用戶自定義函數(shù)
iterator_count — 計算迭代器中元素的個數(shù)
iterator_to_array — 將迭代器中的元素拷貝到數(shù)組
spl_autoload_functions — 返回所有已注冊的__autoload()函數(shù)
spl_autoload_unregister — 注銷已注冊的__autoload()函數(shù)
spl_classes — 返回所有可用的SPL類
spl_object_hash — 返回指定對象的hash id
如iterator相關(guān)函數(shù)使用:
$iterator = new ArrayIterator (array( 'recipe' => 'pancakes' , 'egg' , 'milk' , 'flour' ));
print_r(iterator_to_array($iterator)); //將迭代器元素轉(zhuǎn)化為數(shù)組
echo iterator_count($iterator); //計算迭代器元素的個數(shù)
print_r(iterator_apply($iterator, 'print_item', array($iterator)));//為迭代器每個元素調(diào)用自定義函數(shù)
function print_item(Iterator $iterator)
{
echo strtoupper ( $iterator -> current ()) . "\n" ;
return TRUE ;
}
相關(guān)文章
php的webservice的wsdl的XML無法顯示問題的解決方法
本篇文章是對php的webservice的wsdl的XML無法顯示問題的解決方法進行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-03-03PHP實現(xiàn)XML與數(shù)據(jù)格式進行轉(zhuǎn)換類實例
這篇文章主要介紹了PHP實現(xiàn)XML與數(shù)據(jù)格式進行轉(zhuǎn)換類,實例分析了php進行XML格式數(shù)據(jù)的方法,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07PHP中explode函數(shù)和split函數(shù)的區(qū)別小結(jié)
相信大家都知道,explode和split在php中都是可以通過特定字符把字符串轉(zhuǎn)換成數(shù)組的,那么explode和split既然是一樣的為什么會有兩個函數(shù)呢,那么explode和split的區(qū)別在哪里呢,下面跟著小編我們一起來看看。2016-08-08