PHP - Ds Vector::get() 函式



PHP 的 Ds\Vector::get() 函式用於檢索向量中給定索引處的值。索引是向量中元素的位置,從“第 0 個”索引開始,到“n-1”結束,其中 n 是向量的長度。

如果指定的索引超出向量的長度或無效,則此函式將丟擲 “OutOfRangeException” 異常。

語法

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

public Ds\Vector::get(int $index): mixed

引數

以下是此函式的引數:

  • $index − 訪問元素的基於 0 的索引。

返回值

此函式返回指定索引處的值。

示例 1

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

<?php 
   $vector = new \Ds\Vector([10, 20, 30, 40, 50]);
   echo "The vector elements are: \n";
   print_r($vector);
   $index = 0;
   echo "The index value is: ".$index;
   echo "\nThe value at the given index ".$index." is: ";
   #using get() function
   print_r($vector->get($index));
?>

輸出

以上程式產生以下輸出:

The vector elements are:
Ds\Vector Object
(
    [0] => 10
    [1] => 20
    [2] => 30
    [3] => 40
    [4] => 50
)
The index value is: 0
The value at the given index 0 is: 10

示例 2

以下是 PHP Ds\Vector::get() 函式的另一個示例。我們使用此函式從該向量 (["Tutorials", "Point", "Tutorix"]) 中檢索指定索引 2 處的元素:

<?php 
   $vector = new \Ds\Vector(["Tutorials", "Point", "Tutorix"]); 
   echo "The vector elements are: \n";
   print_r($vector);
   $index = 2;
   echo "The index value is: ".$index;
   echo "\nThe element at the given index ".$index." is: ";
   print_r($vector->get($index));
?>

輸出

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

The vector elements are: 
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => Tutorix
)
The index value is: 2
The element at the given index 2 is: Tutorix

示例 3

如果指定的索引值無效,則 get() 函式會丟擲“OutOfRangeException”異常:

<?php 
   $vector = new \Ds\Vector(['a', 'e', 'i', 'o', 'u']); 
   echo "The vector elements are: \n";
   print_r($vector);
   $index = 10;
   echo "The index value is: ".$index;
   echo "\nThe element at the given index ".$index." is: ";
   print_r($vector->get($index));
?>

輸出

以上程式丟擲如下異常:

The vector elements are:
Ds\Vector Object
(
    [0] => a
    [1] => e
    [2] => i
    [3] => o
    [4] => u
)
The index value is: 10
The element at the given index 10 is: PHP Fatal error:  
Uncaught OutOfRangeException: Index out of range: 10, expected 0 <= x <= 4 in C:\Apache24\htdocs\index.php:8
Stack trace:
#0 C:\Apache24\htdocs\index.php(8): Ds\Vector->get(10)
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 8
php_function_reference.htm
廣告