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 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles