PHP - Ds\Stack::pop() 函式



PHP 的 Ds\Stack::pop() 函式用於移除並檢索當前棧頂部的值。

眾所周知,棧遵循 LIFO(後進先出)原則,最後一個新增的元素將被移除,即棧頂部的元素。如果棧為空 ([]),此函式將丟擲“UnderflowException”異常。

語法

以下是 PHP Ds\Stack::pop() 函式的語法:

public Ds\Stack::pop(): mixed

引數

此函式不接受任何引數。

返回值

此函式返回棧頂被移除的值。

示例 1

以下程式演示了 PHP Ds\Stack::pop() 函式的使用:

<?php 
   $stack = new \Ds\Stack([10, 20, 30]);
   echo "The original stack elements are: \n";
   print_r($stack);
   echo "The stack elements after called pop() function: \n";
   #using pop() function
   $stack->pop();
   print_r($stack);
?>

輸出

上述程式產生以下輸出:

The original stack elements are:
Ds\Stack Object
(
    [0] => 30
    [1] => 20
    [2] => 10
)
The stack elements after called pop() function:
Ds\Stack Object
(
    [0] => 20
    [1] => 10
)

示例 2

以下是 PHP Ds\Stack::pop() 函式的另一個示例。我們使用此函式來移除並檢索當前例項的已移除元素。

<?php 
   $stack = new \Ds\Stack(['a', 'e', 'i']);
   $stack->push('o');
   $stack->push('u');
   echo "The original stack elements are: \n";
   print_r($stack);
   #using pop() function
   echo "The removed elements: ";
   print_r($stack->pop());
   echo "\nThe stack elements after pop() function called: \n";
   print_r($stack);
?>

輸出

執行上述程式後,將顯示以下輸出

The original stack elements are:
Ds\Stack Object
(
    [0] => u
    [1] => o
    [2] => i
    [3] => e
    [4] => a
)
The removed elements: u
The stack elements after pop() function called:
Ds\Stack Object
(
    [0] => o
    [1] => i
    [2] => e
    [3] => a
)

示例 3

如果當前棧為空 ([]),此函式將丟擲“UnderflowException”異常。

<?php 
   $stack = new \Ds\Stack([ ]);
   echo "The original stack elements are: \n";
   print_r($stack);
   #using pop() function
   echo "The removed elements: ";
   print_r($stack->pop());
   echo "\nThe stack elements after pop() function called: \n";
   print_r($stack);
?>

輸出

上述程式丟擲以下異常:

The original stack elements are:
Ds\Stack Object
(
)
The removed elements: PHP Fatal error:  
Uncaught UnderflowException: Unexpected empty state in C:\Apache24\htdocs\index.php:7
Stack trace:
#0 C:\Apache24\htdocs\index.php(7): Ds\Stack->pop()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 7
php_function_reference.htm
廣告