PHP - Ds Map::last() 函式



PHP 的Ds\Map::last()函式用於檢索對映中的最後一對。這對指的是對映元素的鍵和值。此函式返回一個包含對映的最後一個鍵值對的陣列。

如果當前對映為空,則此函式會丟擲UnderflowException異常,表明沒有元素可檢索。

語法

以下是 PHP Ds\Map::last() 函式的語法:

public Ds\Pair Ds\Map::last(); Ds\Pair

引數

此函式不接受任何引數。

返回值。

此函式返回對映的最後一對。

示例 1

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

<?php 
   $map = new \Ds\Map([1, 2, 3]);
   echo "The map elements are: \n";
   print_r($map);
   echo "The last pair of the map: \n";
   #using last() function
   print_r($map->last()); 
?>

輸出

上述程式生成以下輸出:

The map elements are:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 0
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => 2
            [value] => 3
        )

)
The last pair of the map:
Ds\Pair Object
(
    [key] => 2
    [value] => 3
)

示例 2

以下是 PHP Ds\Map::last() 函式的另一個示例。我們使用此函式來檢索此對映 (["Tutorials", "Point", "India"]) 上的最後一對:

<?php 
   $map = new \Ds\Map(["Tutorials", "Point", "India"]);
   echo "The map elements are: \n";   
   print_r($map);
   echo "The last pair of the map: \b";
   #using last() function
   print_r($map->last()); 
?>

輸出

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

The map elements are:
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 0
            [value] => Tutorials
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => Point
        )

    [2] => Ds\Pair Object
        (
            [key] => 2
            [value] => India
        )

)
The last pair of the map: \bDs\Pair Object
(
    [key] => 2
    [value] => India
)

示例 3

如果當前對映為空,此函式將丟擲“UnderflowException”異常。

<?php 
   $map = new \Ds\Map([]); 
   echo "The map elements are: \n";
   print_r($map);
   echo "The last pair of a map: \n";
   #using the last() function
   print_r($map->last()); 
?>

輸出

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

The map elements are:
Ds\Map Object
(
)
The last pair of a map:
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\Map->last()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 7
php_function_reference.htm
廣告