PHP - Ds Vector::last() 函式



PHP 的Ds\Vector::last() 函式用於檢索向量中的最後一個值。如果當前向量為空([]),則此函式會丟擲“UnderflowException”異常。

Ds\Vector 類還提供了一個get() 函式,允許您檢索指定索引處的數值。如果將索引指定為“count() - 1”,則可以檢索向量中的最後一個元素。count() 函式返回向量的長度。

語法

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

public mixed Ds\Vector::last( void )

引數

此函式不接受任何引數。

返回值

此函式返回向量中的最後一個值。

示例 1

以下演示了 PHP Ds\Vector::last() 函式的使用:

<?php 
   $vector = new \Ds\Vector([10, 20, 30, 40, 50]);
   echo "The vector elements are: \n";
   print_r($vector);
   echo("The last element of vector: ");
   #using last() function
   var_dump($vector->last()); 
?>

輸出

上述程式生成以下輸出:

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

示例 2

以下是 PHP Ds\Vector::last() 函式的另一個示例。我們使用此函式來檢索此向量(["Tutorials", "Point", "Tutorix", "e-learning"]) 的最後一個元素:

<?php 
   $vector = new \Ds\Vector(
   ["Tutorials", 
   "Point", 
   "Tutorix", 
   "e-learning"]);
   echo "The vector elements are: \n";
   print_r($vector);   
   echo("The last element of vector: "); 
   var_dump($vector->last());
?>

輸出

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

The vector elements are:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => Tutorix
    [3] => e-learning
)
The last element of vector: string(10) "e-learning"

示例 3

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

<?php 
   $vector = new \Ds\Vector([]);
   echo "The vector elements are: \n";
   print_r($vector);   
   echo("The last element of vector: "); 
   var_dump($vector->last());
?>

輸出

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

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