PHP - Ds Vector::pop() 函式



PHP 的 Ds\Sequence::pop() 函式用於從向量中移除最後一個值,並返回移除的值。

此函式會影響原始向量,這意味著如果您嘗試在呼叫 pop() 函式後列印向量,則向量中將不再包含最後一個元素。

如果當前向量為空 ([]),則會丟擲 UnderflowException 異常。

語法

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

public Ds\Vector::pop(): mixed

引數

此函式不接受任何引數。

返回值

此函式返回移除的最後一個值。

示例 1

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

<?php 
   $vector = new \Ds\Vector([10, 20, 30, 40, 50]);
   echo("The original vector elements: \n"); 
   print_r($vector);
   echo("The last element in vector is: ");
   print_r($vector->pop()); 
?>

輸出

上述程式產生以下輸出:

The original vector elements:
Ds\Vector Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The last element in vector is: 50

示例 2

以下是 PHP Ds\Sequence::pop() 函式的另一個示例。我們使用此函式來移除並檢索此向量的最後一個值(["Tutorials", "Point", "India"]):

<?php 
   $vector = new \Ds\Vector(["Tutorials", "Point", "India"]);
   echo "The vector elements are: \n";
   print_r($vector);
   echo "The removed last element in vector: ";
   print_r($vector->pop());
   echo "\nThe updated vector is: \n";
   print_r($vector);
?>

輸出

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

The vector elements are:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)
The removed last element in vector: India
The updated vector is:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
)

示例 3

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

<?php 
   $vector = new \Ds\Vector([]);
   echo "The vector elements are: \n";
   print_r($vector);
   echo "The removed last element in vector: ";
   print_r($vector->pop());
   echo "\nThe updated vector is: \n";
   print_r($vector);
?>

輸出

執行上述程式後,將丟擲以下異常:

The vector elements are:
Ds\Vector Object
(
)
The removed last element in vector: 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\Vector->pop()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 6
php_function_reference.htm
廣告