PHP - Ds Vector::set() 函式



PHP 的 Ds\Vector::set() 函式用於使用指定值更新向量中給定索引處的現有值。

如果指定的索引值無效,此函式將丟擲“OutOfRangeException”異常。無效索引可以為負數或超過向量的長度。

語法

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

public void Ds\Vector::set( int $index, mixed $value )

引數

以下是此函式的引數:

  • $index - 要更新的值的索引。
  • $value - 將替換現有值的新值。

返回值

此函式不返回值。

示例 1

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

<?php 
   $vector = new \Ds\Vector([1, 2, 3, 4, 5]);
   echo "The original vector: \n";   
   print_r($vector);
   $index = 1;
   $value = 10;
   echo "The index is: ".$index;
   echo "\nThe given value is: ".$value;
   #using vector() function
   $vector->set($index, $value);
   echo("\nThe vector after updating an element: \n"); 
   print_r($vector); 
?>

輸出

上述程式產生以下輸出:

The original vector:
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
The index is: 1
The given value is: 10
The vector after updating an element:
Ds\Vector Object
(
    [0] => 1
    [1] => 10
    [2] => 3
    [3] => 4
    [4] => 5
)

示例 2

以下是 PHP Ds\Vector::set() 函式的另一個示例。我們使用此函式更新此向量(["Tutorials", "Point", "India"]) 指定索引“2”處的現有值:

<?php 
   $vector = new \Ds\Vector(["Tutorials", "Point", "India"]);
   echo "The original vector: \n";   
   print_r($vector);
   $index = 2;
   $value = "Tutorix";
   echo "The index is: ".$index;
   echo "\nThe given value: ".$value;
   #using set() function
   $vector->set($index, $value);
   echo("\nThe vector after updating an element: \n"); 
   print_r($vector); 
?>

輸出

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

The original vector:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => India
)
The index is: 2
The given value: Tutorix
The vector after updating an element:
Ds\Vector Object
(
    [0] => Tutorials
    [1] => Point
    [2] => Tutorix
)

示例 3

如果給定的索引無效set() 函式將丟擲“OutOfRangeException”異常:

<?php 
   $vector = new \Ds\Vector(['a', 'e', 'i', 'o', 'u']);
   echo "The original vector: \n";   
   print_r($vector);
   $index = -1;
   $value = "A";
   echo "The index is: ".$index;
   echo "\nThe given value: ".$value;
   #using set() function
   $vector->set($index, $value);
   echo("\nThe vector after updating an element: \n"); 
   print_r($vector); 
?>

輸出

執行上述程式後,將生成以下輸出:

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