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



PHP 的 Ds\Stack::peek() 函式用於檢索當前棧頂部的值。由於棧遵循 **LIFO**(後進先出)原則,因此最後一個元素始終新增到棧的頂部。

例如,如果一個棧包含三個元素 [10, 20, 30],則頂部元素將是 30。如果當前棧為空 ([]), 此函式將丟擲 UnderflowException 異常。

語法

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

public Ds\Stack::peek(): mixed

引數

此函式不接受任何引數。

返回值

此函式返回棧頂部的值。

示例 1

以下是 PHP Ds\Stack::peek() 函式的基本示例:

<?php 
   $stack = new \Ds\Stack([10, 20, 30, 40]);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The element present at top of the stack is: ";
   #using peek() function   
   print_r($stack->peek());
?>

輸出

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

The stack elements are:
Ds\Stack Object
(
    [0] => 40
    [1] => 30
    [2] => 20
    [3] => 10
)
The element present at top of the stack is: 40

示例 2

以下是 PHP Ds\Stack::peek() 函式的另一個示例。此函式用於檢索此棧 [("Tutorials", "Point", "India")] 頂部的元素:

<?php 
   $stack = new \Ds\Stack();
   $stack->push("Tutorials", "Point", "India"); 
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The element present at top of the stack is: ";
   print_r($stack->peek()); 
?>

輸出

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

The stack elements are:
Ds\Stack Object
(
    [0] => India
    [1] => Point
    [2] => Tutorials
)
The element present at top of the stack is: India

示例 3

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

<?php 
   $stack = new \Ds\Stack([]);
   echo "The stack elements are: \n";
   print_r($stack);
   echo "The element present at top of the stack is: ";
   print_r($stack->peek()); 
?>

輸出

上述程式丟擲以下異常:

The stack elements are:
Ds\Stack Object
(
)
The element present at top of the stack is: PHP Fatal error:  
Uncaught UnderflowException: Unexpected empty state in C:\Apache24\htdocs\index.php:6
Stack trace:
#0 C:\Apache24\htdocs\index.php(6): Ds\Stack->peek()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 6
php_function_reference.htm
廣告