PHP - Ds Vector::first() 函式



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

Ds\Vector 類還提供了一個 get() 函式,允許您檢索指定索引處的 value。如果將索引指定為 0,則可以檢索向量中的第一個元素。

語法

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

public Ds\Vector::first(): mixed

引數

此函式不接受任何引數。

返回值

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

示例 1

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

<?php
   $vector = new \Ds\Vector([1, 2, 3, 4, 5]);
   echo "The vector elements are: \n";
   print_r($vector);
   echo("The first element of vector: "); 
   var_dump($vector->first());
?>

輸出

上述程式輸出如下:

The vector elements are:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The first element of vector: int(1)

示例 2

以下是 PHP Ds\Vector::first() 函式的另一個示例。我們使用此函式來檢索此向量 (["Tutorials", "Point", "India"]) 中的第一個元素:

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

輸出

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

The vector elements are:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)
The first element of vector: string(9) "Tutorials"

示例 3

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

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

輸出

上述程式丟擲以下異常:

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