Home Backend Development PHP Tutorial PHP standard library

PHP standard library

Apr 28, 2018 am 11:49 AM
php standard

This article mainly introduces the standard library of PHP, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

Redirect: https://www.cnblogs.com /yafang/p/5872187.html 

1. What is SPL?

SPL is a collection of interfaces and classes used to solve standard problems. (From: http://php.net/manual/zh/intro.spl.php)

SPL, PHP Standard Library (Standard PHP Library), built-in components and interfaces starting from PHP 5.0, and from PHP5.3 has gradually matured. SPL is built into all PHP5 development environments and requires no setup.

2. How to use?

SPL provides a set of standard data structures:

Doubly linked list


    • ##SplStack

    • SplQueue

    • SplDoublyLinkedList

A doubly linked list is a An important linear storage structure, for each node in the doubly linked list, it not only stores its own information, but also stores the addresses of the predecessor and successor nodes.

The SplDoublyLinkedList class in PHP SPL provides operations on doubly linked lists.

The summary of the SplDoublyLinkedList class is as follows:


PHP standard library

 1 SplDoublyLinkedList implements Iterator  , ArrayAccess  , Countable  { 
 2    
 3   public __construct ( void ) 
 4   public void add ( mixed $index , mixed $newval ) 
 5   //双链表的头部节点 
 6   public mixed top ( void ) 
 7   //双链表的尾部节点 
 8   public mixed bottom ( void ) 
 9   //双联表元素的个数
 10   public int count ( void )
 11   //检测双链表是否为空
 12   public bool isEmpty ( void )
 13   
 14   
 15   //当前节点索引
 16   public mixed key ( void )
 17   //移到上条记录
 18   public void prev ( void )
 19   //移到下条记录
 20   public void next ( void )
 21   //当前记录
 22   public mixed current ( void )
 23   //将指针指向迭代开始处
 24   public void rewind ( void )
 25   //检查双链表是否还有节点
 26   public bool valid ( void )
 27   
 28   //指定index处节点是否存在
 29   public bool offsetExists ( mixed $index )
 30   //获取指定index处节点值
 31   public mixed offsetGet ( mixed $index )
 32   //设置指定index处值
 33   public void offsetSet ( mixed $index , mixed $newval )
 34   //删除指定index处节点
 35   public void offsetUnset ( mixed $index )
 36   
 37   //从双链表的尾部弹出元素
 38   public mixed pop ( void )
 39   //添加元素到双链表的尾部
 40   public void push ( mixed $value )
 41   
 42   //序列化存储
 43   public string serialize ( void )
 44   //反序列化
 45   public void unserialize ( string $serialized )
 46   
 47   //设置迭代模式
 48   public void setIteratorMode ( int $mode )
 49   //获取迭代模式SplDoublyLinkedList::IT_MODE_LIFO (Stack style) SplDoublyLinkedList::IT_MODE_FIFO (Queue style)
 50   public int getIteratorMode ( void )
 51   
 52   //双链表的头部移除元素
 53   public mixed shift ( void )
 54   //双链表的头部添加元素
 55   public void unshift ( mixed $value )
 56   
 57 }
Copy after login

PHP standard library

 
1 $list = new SplDoublyLinkedList(); 
2 $list->push('a'); 
3 $list->push('b'); 
4 $list->push('c');
5 $list->push('d'); 
6  
7 $list->unshift('top'); 
8 $list->shift(); 
9 
10 $list->rewind();//rewind操作用于把节点指针指向Bottom所在的节点
11 echo 'curren node:'.$list->current()."<br>";//获取当前节点
12 
13 $list->next();//指针指向下一个节点
14 echo 'next node:'.$list->current()."<br>";
15 
16 $list->next();
17 $list->next();
18 $list->prev();//指针指向上一个节点
19 echo 'next node:'.$list->current()."<br>";
20 
21 if($list->current())
22     echo 'current node is valid<br>';
23 else
24     echo 'current node is invalid<br>';
25 
26 
27 if($list->valid())//如果当前节点是有效节点,valid返回true
28     echo "valid list<br>";
29 else
30     echo "invalid list <br>";
31 
32 
33 var_dump(array(
34     'pop' => $list->pop(),
35     'count' => $list->count(),
36     'isEmpty' => $list->isEmpty(),
37     'bottom' => $list->bottom(),
38     'top' => $list->top()
39 )); 
40 
41 $list->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO);
42 var_dump($list->getIteratorMode());
43 
44 for($list->rewind(); $list->valid(); $list->next()) {
45     echo $list->current().PHP_EOL;
46 }
47 
48 var_dump($a = $list->serialize());
49 //print_r($list->unserialize($a));
50 
51 $list->offsetSet(0,'new one');
52 $list->offsetUnset(0);
53 var_dump(array(
54     'offsetExists' => $list->offsetExists(4),
55     'offsetGet' => $list->offsetGet(0),
56 
57 ));
58 var_dump($list);
59 
60 //堆栈,先进后出
61 $stack = new SplStack();//继承自SplDoublyLinkedList类
62 
63 $stack->push("a<br>");
64 $stack->push("b<br>");
65 
66 echo $stack->pop();
67 echo $stack->pop();
68 echo $stack->offsetSet(0,'B');//堆栈的offset=0是Top所在的位置,offset=1是Top位置节点靠近bottom位置的相邻节点,以此类推
69 $stack->rewind();//双向链表的rewind和堆栈的rewind相反,堆栈的rewind使得当前指针指向Top所在的位置,而双向链表调用之后指向bottom所在位置70 echo 'current:'.$stack->current().'<br>';
71 
72 $stack->next();//堆栈的next操作使指针指向靠近bottom位置的下一个节点,而双向链表是靠近top的下一个节点
73 echo 'current:'.$stack->current().'<br>';
74 echo '<br><br>';
75 
76 //队列,先进先出
77 $queue = new SplQueue();//继承自SplDoublyLinkedList类
78 
79 $queue->enqueue("a<br>");//插入一个节点到队列里面的Top位置
80 $queue->enqueue("b<br>");
81 
82 $queue->offsetSet(0,'A');//堆栈的offset=0是Top所在的位置,offset=1是Top位置节点靠近bottom位置的相邻节点,以此类推
83 
84 echo $queue->dequeue();
85 echo $queue->dequeue();
86 
87 echo "<br><br>";
Copy after login

PHP standard library

    堆


    • SplMaxHeap

    • SplMinHeap

    • SplHeap

    堆(Heap)就是为了实现优先队列而设计的一种数据结构,它是通过构造二叉堆(二叉树的一种)实现。根节点最大的堆叫做最大堆或大根堆(SplMaxHeap),根节点最小的堆叫做最小堆或小根堆(SplMinHeap)。二叉堆还常用于排序(堆排序)。

    SplHeap类摘要如下:

PHP standard library

1 abstract SplHeap implements Iterator , Countable {
2   /* 方法 */ 
3   public __construct ( void ) 
4   abstract protected int compare ( mixed $value1 , mixed $value2 ) 
5   public int count ( void ) 
6   public mixed current ( void ) 
7   public mixed extract ( void ) 
8   public void insert ( mixed $value ) 
9   public bool isEmpty ( void )
10   public mixed key ( void )
11   public void next ( void )
12   public void recoverFromCorruption ( void )
13   public void rewind ( void )
14   public mixed top ( void )
15   public bool valid ( void )
16 }
Copy after login

PHP standard library

    显然它是一个抽象类,最大堆(SplMaxHeap)和最小堆(SplMinHeap)就是继承它实现的。最大堆和最小堆并没有额外的方法。

SplHeap简单使用:

PHP standard library

1 //堆 
2 class MySplHeap extends SplHeap{ 
3     //compare()方法用来比较两个元素的大小,绝对他们在堆中的位置 
4     public function compare( $value1, $value2 ) { 
5         return ( $value1 - $value2 ); 
6     } 
7 } 
8  
9 $obj = new MySplHeap();
10 
11 $obj->insert(0);
12 $obj->insert(1);
13 $obj->insert(2);
14 $obj->insert(3);
15 $obj->insert(4);
16 
17 echo $obj->top();//4
18 echo $obj->count();//5
19 
20 foreach ($obj as $item) {
21     echo $item."<br>";
22 }
Copy after login

PHP standard library 

    队列


    • SplPriorityQueue

优先队列也是非常实用的一种数据结构,可以通过加权对值进行排序,由于排序在php内部实现,业务代码中将精简不少而且更高效。通过SplPriorityQueue::setExtractFlags(int  $flag)设置提取方式可以提取数据(等同最大堆)、优先级、和两者都提取的方式。

    SplPriorityQueue类摘要如下:

PHP standard library

1 SplPriorityQueue implements Iterator , Countable { 
2   /* 方法 */ 
3   public __construct ( void ) 
4   public int compare ( mixed $priority1 , mixed $priority2 ) 
5   public int count ( void ) 
6   public mixed current ( void ) 
7   public mixed extract ( void ) 
8   public void insert ( mixed $value , mixed $priority ) 
9   public bool isEmpty ( void )
10   public mixed key ( void )
11   public void next ( void )
12   public void recoverFromCorruption ( void )
13   public void rewind ( void )
14   public void setExtractFlags ( int $flags )
15   public mixed top ( void )
16   public bool valid ( void )
17 }
Copy after login

PHP standard library

    简单使用:

PHP standard library

1 $pq = new SplPriorityQueue(); 
2  
3 $pq->insert('a', 10); 
4 $pq->insert('b', 1); 
5 $pq->insert('c', 8); 
6  
7 echo $pq->count() .PHP_EOL; //3 
8 echo $pq->current() . PHP_EOL; //a 
9 
10 /**
11  * 设置元素出队模式
12  * SplPriorityQueue::EXTR_DATA 仅提取值
13  * SplPriorityQueue::EXTR_PRIORITY 仅提取优先级
14  * SplPriorityQueue::EXTR_BOTH 提取数组包含值和优先级
15  */
16 $pq->setExtractFlags(SplPriorityQueue::EXTR_DATA);
17 
18 while($pq->valid()) {
19     print_r($pq->current());  //a  c  b
20     $pq->next();
21 }
Copy after login

PHP standard library

    阵列


    • SplFixedArray

SplFixedArray主要是处理数组相关的主要功能,与普通php array不同的是,它是固定长度的,且以数字为键名的数组,优势就是比普通的数组处理更快。通常情况下SplFixedArray要比php array快上20%~30%,所以如果你是处理巨大数量的固定长度数组,还是强烈建议使用。

SplFixedArray类摘要如下:

PHP standard library

1 SplFixedArray implements Iterator , ArrayAccess , Countable {
2   /* 方法 */ 
3   public __construct ([ int $size = 0 ] ) 
4   public int count ( void ) 
5   public mixed current ( void ) 
6   public static SplFixedArray fromArray ( array $array [, bool $save_indexes = true ] ) 
7   public int getSize ( void ) 
8   public int key ( void ) 
9   public void next ( void )
10   public bool offsetExists ( int $index )
11   public mixed offsetGet ( int $index )
12   public void offsetSet ( int $index , mixed $newval )
13   public void offsetUnset ( int $index )
14   public void rewind ( void )
15   public int setSize ( int $size )
16   public array toArray ( void )
17   public bool valid ( void )
18   public void __wakeup ( void )
19 }
Copy after login

PHP standard library

简单使用:

PHP standard library

1 $arr = new SplFixedArray(4);
2 $arr[0] = 'php'; 
3 $arr[1] = 1; 
4 $arr[3] = 'python'; 
5  
6 //遍历, $arr[2] 为null 
7 foreach($arr as $v) { 
8     echo $v . PHP_EOL; 
9 }
10 
11 //获取数组长度
12 echo $arr->getSize(); //4
13 
14 //增加数组长度
15 $arr->setSize(5);
16 $arr[4] = 'new one';
17 
18 //捕获异常
19 try{
20     echo $arr[10];
21 } catch (RuntimeException $e) {
22     echo $e->getMessage();
23 }
Copy after login

PHP standard library

    映射


    • SplObjectStorage

用来存储一组对象的,特别是当你需要唯一标识对象的时候。

PHP SPL SplObjectStorage类实现了Countable,Iterator,Serializable,ArrayAccess四个接口。可实现统计、迭代、序列化、数组式访问等功能。

SplObjectStorage类摘要如下:

PHP standard library

1 SplObjectStorage implements Countable , Iterator , Serializable , ArrayAccess { 
2   /* 方法 */ 
3   public void addAll ( SplObjectStorage $storage ) 
4   public void attach ( object $object [, mixed $data = NULL ] ) 
5   public bool contains ( object $object ) 
6   public int count ( void ) 
7   public object current ( void ) 
8   public void detach ( object $object ) 
9   public string getHash ( object $object )
10   public mixed getInfo ( void )
11   public int key ( void )
12   public void next ( void )
13   public bool offsetExists ( object $object )
14   public mixed offsetGet ( object $object )
15   public void offsetSet ( object $object [, mixed $data = NULL ] )
16   public void offsetUnset ( object $object )
17   public void removeAll ( SplObjectStorage $storage )
18   public void removeAllExcept ( SplObjectStorage $storage )
19   public void rewind ( void )
20   public string serialize ( void )
21   public void setInfo ( mixed $data )
22   public void unserialize ( string $serialized )
23   public bool valid ( void )
24 }
Copy after login

PHP standard library

    简单使用:

PHP standard library

1 class A { 
2     public $i; 
3     public function __construct($i) { 
4         $this->i = $i; 
5     } 
6 } 
7   
8 $a1 = new A(1); 
9 $a2 = new A(2);
10 $a3 = new A(3);
11 $a4 = new A(4);
12  
13 $container = new SplObjectStorage();
14  
15 //SplObjectStorage::attach 添加对象到Storage中
16 $container->attach($a1);
17 $container->attach($a2);
18 $container->attach($a3);
19  
20 //SplObjectStorage::detach 将对象从Storage中移除
21 $container->detach($a2);
22  
23 //SplObjectStorage::contains用于检查对象是否存在Storage中
24 var_dump($container->contains($a1)); //true
25 var_dump($container->contains($a4)); //false
26  
27 //遍历
28 $container->rewind();
29 while($container->valid()) {
30     var_dump($container->current());
31     $container->next();
32 }
Copy after login

The above is the detailed content of PHP standard library. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1252
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles