大牛就是大牛。。。。。。沒得黑
splphp
附上:
PHP模版解析類
峯哥原文
新手文章明顯不懂背後原理,但php代碼很詳細,值得一看也不得不說他付出過努力和有一點點「天分」,若是他能幾個月對代碼由陌生變熟悉,還有幾個調試技巧,這文章新手熟手都值得看看html
這幾天,我在學習PHP語言中的SPL。
這個東西應該屬於PHP中的高級內容,看上去很複雜,可是很是有用,因此我作了長篇筆記。否則記不住,之後要用的時候,仍是要從頭學起。mysql
PHP SPL筆記
目錄
第一部分 簡介
1. 什麼是SPL?
2. 什麼是Iterator?
第二部分 SPL Interfaces
3. Iterator界面
4. ArrayAccess界面
5. IteratorAggregate界面
6. RecursiveIterator界面
7. SeekableIterator界面
8. Countable界面
第三部分 SPL Classes
9. SPL的內置類
10. DirectoryIterator類
11. ArrayObject類
12. ArrayIterator類
13. RecursiveArrayIterator類和RecursiveIteratorIterator類
14. FilterIterator類
15. SimpleXMLIterator類
16. CachingIterator類
17. LimitIterator類
18. SplFileObject類
第一部 簡介
1. 什麼是SPL?
SPL是Standard PHP Library(PHP標準庫)的縮寫。
根據官方定義,它是」a collection of interfaces and classes that are meant to solve standard problems」。可是,目前在使用中,SPL更多地被看做是一種使object(物體)模仿array(數組)行爲的interfaces和classes。
2. 什麼是Iterator?
SPL的核心概念就是Iterator。這指的是一種Design Pattern,根據《Design Patterns》一書的定義,Iterator的做用是」provide an object which traverses some aggregate structure, abstracting away assumptions about the implementation of that structure.」
wikipedia中說,」an iterator is an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation」…….」the iterator pattern is a design pattern in which iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation」.
通俗地說,Iterator可以使許多不一樣的數據結構,都能有統一的操做界面,好比一個數據庫的結果集、同一個目錄中的文件集、或者一個文本中每一行構成的集合。
若是按照普通狀況,遍歷一個MySQL的結果集,程序須要這樣寫:程序員
// Fetch the 「aggregate structure」
$result = mysql_query(「SELECT * FROM users」);算法
// Iterate over the structure
while ( row=myresult) ) {
// do stuff with the row here
}sql
讀出一個目錄中的內容,須要這樣寫:數據庫
// Fetch the 「aggregate structure」
$dh = opendir(‘/home/harryf/files’);數組
// Iterate over the structure
while ( fdh) ) {
// do stuff with the file here
}markdown
讀出一個文本文件的內容,須要這樣寫:數據結構
// Fetch the 「aggregate structure」
$fh = fopen(「/home/hfuecks/files/results.txt」, 「r」);
// Iterate over the structure
while (!feof($fh)) {
line=ffh);
// do stuff with the line here
}
上面三段代碼,雖然處理的是不一樣的resource(資源),可是功能都是遍歷結果集(loop over contents),所以Iterator的基本思想,就是將這三種不一樣的操做統一塊兒來,用一樣的命令界面,處理不一樣的資源。
第二部分 SPL Interfaces
3. Iterator界面
SPL規定,全部部署了Iterator界面的class,均可以用在foreach Loop中。Iterator界面中包含5個必須部署的方法:
* current() This method returns the current index's value. You are solely responsible for tracking what the current index is as the interface does not do this for you. * key() This method returns the value of the current index's key. For foreach loops this is extremely important so that the key value can be populated. * next() This method moves the internal index forward one entry. * rewind() This method should reset the internal index to the first element. * valid() This method should return true or false if there is a current element. It is called after rewind() or next().
下面就是一個部署了Iterator界面的class示例:
/**
* An iterator for native PHP arrays, re-inventing the wheel
*
* Notice the 「implements Iterator」 - important!
*/
class ArrayReloaded implements Iterator {
/**
* A native PHP array to iterate over
*/
private $array = array();
/**
* A switch to keep track of the end of the array
*/
private $valid = FALSE;
/**
* Constructor
* @param array native PHP array to iterate over
*/
function __construct(array) {this->array = $array;
}
/**
* Return the array 「pointer」 to the first element
* PHP’s reset() returns false if the array has no elements
*/
function rewind(){
this−>validthis->array));
}
/**
* Return the current array element
*/
function current(){
return current($this->array);
}
/**
* Return the key of the current array element
*/
function key(){
return key($this->array);
}
/**
* Move forward by one
* PHP’s next() returns false if there are no more elements
*/
function next(){
this−>validthis->array));
}
/**
* Is the current element valid?
*/
function valid(){
return $this->valid;
}
}
使用方法以下:
// Create iterator object
$colors = new ArrayReloaded(array (‘red’,’green’,’blue’,));
// Iterate away!
foreach ( colorsascolor ) {
echo $color.」 」;
}
你也能夠在foreach循環中使用key()方法:
// Display the keys as well
foreach ( colorsaskey => color ) { echo 「key: $color 」;
}
除了foreach循環外,也可使用while循環,
// Reset the iterator - foreach does this automatically
$colors->rewind();
// Loop while valid
while ( $colors->valid() ) {
echo colors−>keycolors->current().」
「;
$colors->next();
}
根據測試,while循環要稍快於foreach循環,由於運行時少了一層中間調用。
4. ArrayAccess界面
部署ArrayAccess界面,可使得object像array那樣操做。ArrayAccess界面包含四個必須部署的方法:
* offsetExists($offset) This method is used to tell php if there is a value for the key specified by offset. It should return true or false. * offsetGet($offset) This method is used to return the value specified by the key offset. * offsetSet($offset, $value) This method is used to set a value within the object, you can throw an exception from this function for a read-only collection. * offsetUnset($offset) This method is used when a value is removed from an array either through unset() or assigning the key a value of null. In the case of numerical arrays, this offset should not be deleted and the array should not be reindexed unless that is specifically the behavior you want.
下面就是一個部署ArrayAccess界面的實例:
/**
* A class that can be used like an array
*/
class Article implements ArrayAccess {
public $title;
public $author;
public $category;
function __construct(title,author,category) {this->title = title;this->author = author;this->category = $category;
}
/**
* Defined by ArrayAccess interface
* Set a value given it’s key e.g. A[‘title′]=‘fkey, value) { if ( array_key_exists(key,get_object_vars(this)) ) {this->{key} =value;
}
}
/**
* Defined by ArrayAccess interface
* Return a value given it’s key e.g. echo A[‘title′];∗@parammixedkey) {
if ( array_key_exists(keythis)) ) {
return this->{key};
}
}
/**
* Defined by ArrayAccess interface
* Unset a value by it’s key e.g. unset(A[‘title′]);∗@parammixedkey) {
if ( array_key_exists(keythis)) ) {
unset(this->{key});
}
}
/**
* Defined by ArrayAccess interface
* Check value exists, given it’s key e.g. isset(A[‘title′])∗@parammixedoffset) {
return array_key_exists(ofthis));
}
}
使用方法以下:
// Create the object
$A = new Article(‘SPL Rocks’,’Joe Bloggs’, ‘PHP’);
// Check what it looks like
echo ‘Initial State:
// Change the title using array syntax
$A[‘title’] = ‘SPL really rocks’;
// Try setting a non existent property (ignored)
$A[‘not found’] = 1;
// Unset the author field
unset($A[‘author’]);
// Check what it looks like again
echo ‘Final State:
運行結果以下:
Initial State:
Article Object
(
[title] => SPL Rocks
[author] => Joe Bloggs
[category] => PHP
)
Final State:
Article Object
(
[title] => SPL really rocks
[category] => PHP
)
能夠看到,$A雖然是一個object,可是徹底能夠像array那樣操做。
你還能夠在讀取數據時,增長程序內部的邏輯:
function offsetGet(key) { if ( array_key_exists(key,get_object_vars(this)) ) { return strtolower(this->{$key});
}
}
class Article implements ArrayAccess, IteratorAggregate {
/**
* Defined by IteratorAggregate interface
* Returns an iterator for for this object, for use with foreach
* @return ArrayIterator
*/
function getIterator() {
return new ArrayIterator($this);
}
使用方法以下:
$A = new Article(‘SPL Rocks’,’Joe Bloggs’, ‘PHP’);
// Loop (getIterator will be called automatically)
echo ‘Looping with foreach:
// Get the size of the iterator (see how many properties are left)
echo 「Object has 「.sizeof($A->getIterator()).」 elements」;
顯示結果以下:
Looping with foreach:
title : SPL Rocks
author : Joe Bloggs
category : PHP
Object has 3 elements
大牛就是大牛。。。。。。沒得黑
spl
附上:
PHP模版解析類
峯哥原文
新手文章明顯不懂背後原理,但php代碼很詳細,值得一看也不得不說他付出過努力和有一點點「天分」,若是他能幾個月對代碼由陌生變熟悉,還有幾個調試技巧,這文章新手熟手都值得看看
這幾天,我在學習PHP語言中的SPL。
這個東西應該屬於PHP中的高級內容,看上去很複雜,可是很是有用,因此我作了長篇筆記。否則記不住,之後要用的時候,仍是要從頭學起。
PHP SPL筆記
目錄
第一部分 簡介
1. 什麼是SPL?
2. 什麼是Iterator?
第二部分 SPL Interfaces
3. Iterator界面
4. ArrayAccess界面
5. IteratorAggregate界面
6. RecursiveIterator界面
7. SeekableIterator界面
8. Countable界面
第三部分 SPL Classes
9. SPL的內置類
10. DirectoryIterator類
11. ArrayObject類
12. ArrayIterator類
13. RecursiveArrayIterator類和RecursiveIteratorIterator類
14. FilterIterator類
15. SimpleXMLIterator類
16. CachingIterator類
17. LimitIterator類
18. SplFileObject類
第一部 簡介
1. 什麼是SPL?
SPL是Standard PHP Library(PHP標準庫)的縮寫。
根據官方定義,它是」a collection of interfaces and classes that are meant to solve standard problems」。可是,目前在使用中,SPL更多地被看做是一種使object(物體)模仿array(數組)行爲的interfaces和classes。
2. 什麼是Iterator?
SPL的核心概念就是Iterator。這指的是一種Design Pattern,根據《Design Patterns》一書的定義,Iterator的做用是」provide an object which traverses some aggregate structure, abstracting away assumptions about the implementation of that structure.」
wikipedia中說,」an iterator is an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation」…….」the iterator pattern is a design pattern in which iterators are used to access the elements of an aggregate object sequentially without exposing its underlying representation」.
通俗地說,Iterator可以使許多不一樣的數據結構,都能有統一的操做界面,好比一個數據庫的結果集、同一個目錄中的文件集、或者一個文本中每一行構成的集合。
若是按照普通狀況,遍歷一個MySQL的結果集,程序須要這樣寫:
// Fetch the 「aggregate structure」
$result = mysql_query(「SELECT * FROM users」);
// Iterate over the structure
while ( row=myresult) ) {
// do stuff with the row here
}
讀出一個目錄中的內容,須要這樣寫:
// Fetch the 「aggregate structure」
$dh = opendir(‘/home/harryf/files’);
// Iterate over the structure
while ( fdh) ) {
// do stuff with the file here
}
讀出一個文本文件的內容,須要這樣寫:
// Fetch the 「aggregate structure」
$fh = fopen(「/home/hfuecks/files/results.txt」, 「r」);
// Iterate over the structure
while (!feof($fh)) {
line=ffh);
// do stuff with the line here
}
上面三段代碼,雖然處理的是不一樣的resource(資源),可是功能都是遍歷結果集(loop over contents),所以Iterator的基本思想,就是將這三種不一樣的操做統一塊兒來,用一樣的命令界面,處理不一樣的資源。
第二部分 SPL Interfaces
3. Iterator界面
SPL規定,全部部署了Iterator界面的class,均可以用在foreach Loop中。Iterator界面中包含5個必須部署的方法:
* current() This method returns the current index's value. You are solely responsible for tracking what the current index is as the interface does not do this for you. * key() This method returns the value of the current index's key. For foreach loops this is extremely important so that the key value can be populated. * next() This method moves the internal index forward one entry. * rewind() This method should reset the internal index to the first element. * valid() This method should return true or false if there is a current element. It is called after rewind() or next().
下面就是一個部署了Iterator界面的class示例:
/**
* An iterator for native PHP arrays, re-inventing the wheel
*
* Notice the 「implements Iterator」 - important!
*/
class ArrayReloaded implements Iterator {
/**
* A native PHP array to iterate over
*/
private $array = array();
/**
* A switch to keep track of the end of the array
*/
private $valid = FALSE;
/**
* Constructor
* @param array native PHP array to iterate over
*/
function __construct(array) {this->array = $array;
}
/**
* Return the array 「pointer」 to the first element
* PHP’s reset() returns false if the array has no elements
*/
function rewind(){
this−>validthis->array));
}
/**
* Return the current array element
*/
function current(){
return current($this->array);
}
/**
* Return the key of the current array element
*/
function key(){
return key($this->array);
}
/**
* Move forward by one
* PHP’s next() returns false if there are no more elements
*/
function next(){
this−>validthis->array));
}
/**
* Is the current element valid?
*/
function valid(){
return $this->valid;
}
}
使用方法以下:
// Create iterator object
$colors = new ArrayReloaded(array (‘red’,’green’,’blue’,));
// Iterate away!
foreach ( colorsascolor ) {
echo $color.」 」;
}
你也能夠在foreach循環中使用key()方法:
// Display the keys as well
foreach ( colorsaskey => color ) { echo 「key: $color 」;
}
除了foreach循環外,也可使用while循環,
// Reset the iterator - foreach does this automatically
$colors->rewind();
// Loop while valid
while ( $colors->valid() ) {
echo colors−>keycolors->current().」
「;
$colors->next();
}
根據測試,while循環要稍快於foreach循環,由於運行時少了一層中間調用。
4. ArrayAccess界面
部署ArrayAccess界面,可使得object像array那樣操做。ArrayAccess界面包含四個必須部署的方法:
* offsetExists($offset) This method is used to tell php if there is a value for the key specified by offset. It should return true or false. * offsetGet($offset) This method is used to return the value specified by the key offset. * offsetSet($offset, $value) This method is used to set a value within the object, you can throw an exception from this function for a read-only collection. * offsetUnset($offset) This method is used when a value is removed from an array either through unset() or assigning the key a value of null. In the case of numerical arrays, this offset should not be deleted and the array should not be reindexed unless that is specifically the behavior you want.
下面就是一個部署ArrayAccess界面的實例:
/**
* A class that can be used like an array
*/
class Article implements ArrayAccess {
public $title;
public $author;
public $category;
function __construct(title,author,category) {this->title = title;this->author = author;this->category = $category;
}
/**
* Defined by ArrayAccess interface
* Set a value given it’s key e.g. A[‘title′]=‘fkey, value) { if ( array_key_exists(key,get_object_vars(this)) ) {this->{key} =value;
}
}
/**
* Defined by ArrayAccess interface
* Return a value given it’s key e.g. echo A[‘title′];∗@parammixedkey) {
if ( array_key_exists(keythis)) ) {
return this->{key};
}
}
/**
* Defined by ArrayAccess interface
* Unset a value by it’s key e.g. unset(A[‘title′]);∗@parammixedkey) {
if ( array_key_exists(keythis)) ) {
unset(this->{key});
}
}
/**
* Defined by ArrayAccess interface
* Check value exists, given it’s key e.g. isset(A[‘title′])∗@parammixedoffset) {
return array_key_exists(ofthis));
}
}
使用方法以下:
// Create the object
$A = new Article(‘SPL Rocks’,’Joe Bloggs’, ‘PHP’);
// Check what it looks like
echo ‘Initial State:
// Change the title using array syntax
$A[‘title’] = ‘SPL really rocks’;
// Try setting a non existent property (ignored)
$A[‘not found’] = 1;
// Unset the author field
unset($A[‘author’]);
// Check what it looks like again
echo ‘Final State:
運行結果以下:
Initial State:
Article Object
(
[title] => SPL Rocks
[author] => Joe Bloggs
[category] => PHP
)
Final State:
Article Object
(
[title] => SPL really rocks
[category] => PHP
)
能夠看到,$A雖然是一個object,可是徹底能夠像array那樣操做。
你還能夠在讀取數據時,增長程序內部的邏輯:
function offsetGet(key) { if ( array_key_exists(key,get_object_vars(this)) ) { return strtolower(this->{$key});
}
}
class Article implements ArrayAccess, IteratorAggregate {
/**
* Defined by IteratorAggregate interface
* Returns an iterator for for this object, for use with foreach
* @return ArrayIterator
*/
function getIterator() {
return new ArrayIterator($this);
}
使用方法以下:
$A = new Article(‘SPL Rocks’,’Joe Bloggs’, ‘PHP’);
// Loop (getIterator will be called automatically)
echo ‘Looping with foreach:
// Get the size of the iterator (see how many properties are left)
echo 「Object has 「.sizeof($A->getIterator()).」 elements」;
顯示結果以下:
Looping with foreach:
title : SPL Rocks
author : Joe Bloggs
category : PHP
Object has 3 elements