PHP - Ds Map::first() 函数



PHP 的 Ds\Map::first() 函数用于检索映射中的第一对。这对指的是映射元素的键和值。此函数返回一个包含映射的第一个键值对的数组。

如果当前映射为空,则此函数会抛出 UnderflowException 异常,指示没有元素可检索。

语法

以下是 PHP Ds\Map::first() 函数的语法:

public Ds\Map::first(): Ds\Pair

参数

此函数不接受任何参数。

返回值

此函数返回映射中的第一对。

示例 1

以下程序演示了 PHP Ds\Map::first() 函数的用法:

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

输出

执行上述程序后,将显示以下输出:

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

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

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

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

)
The first pair of a map:
Ds\Pair Object
(
    [key] => 0
    [value] => 10
)

示例 2

以下是 Ds\Map::first() 函数的另一个示例。我们使用此函数来检索此映射 (["Tutorials", "Point", "India"]) 的第一对:

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

输出

上述程序生成以下输出:

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 first pair of a map:
Ds\Pair Object
(
    [key] => 0
    [value] => Tutorials
)

示例 3

如果当前映射为空,则此函数会抛出 "UnderflowException" 异常。

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

输出

执行上述程序后,将生成以下输出:

The map elements are:
Ds\Map Object
(
)
The first 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->first()
#1 {main}
  thrown in C:\Apache24\htdocs\index.php on line 7
php_function_reference.htm
广告
© . All rights reserved.