我想在函数内定义一个关联多维数组,并使该数组中的索引(小数组)成为函数内的参数我还想限制这些索引的数据类型(int,float,string)
当调用 时,用户不允许在函数参数中输入其他数据类型。我会这样做:
<?php
/**
* Print some data for a given index.
*
* @param $index The index should be an int, a float or a string.
* @throws TypeError when the index is in the bad type.
* @throws OutOfRangeException when the index doesn't exist in the data array.
*/
function print_data($index) {
static $data = [
0 => 'element with int index',
1.5 => 'element with float index',
'firstname' => 'James',
];
if (!is_numeric($index) && !is_string($index)) {
throw new TypeError('The given index is not in the valid type!');
}
if (!isset($data[$index])) {
throw new OutOfRangeException('The given index does not exist in the data!');
}
print "Value of index $index is: $data[$index]" . PHP_EOL;
}
$index_tests = [
0,
1.5,
'firstname',
true, // Wrong index type.
-2, // Correct type but missing index.
'lastname', // Correct type but missing index.
['An array'], // Wrong index type.
new DateTime(), // Wrong index type.
];
foreach ($index_tests as $index) {
try {
print_data($index);
}
catch (TypeError | OutOfRangeException $e) {
print 'Error with ' . var_export($index, true) . ': ' . $e->getMessage() . PHP_EOL;
}
}
?>
它将输出如下内容:
Value of index 0 is: element with int index
Value of index 1.5 is: element with float index
Value of index firstname is: James
Error with true: The given index is not in the valid type!
Error with -2: The given index does not exist in the data!
Error with 'lastname': The given index does not exist in the data!
Error with array (
0 => 'An array',
): The given index is not in the valid type!
Error with DateTime::__set_state(array(
'date' => '2022-04-21 07:53:54.087321',
'timezone_type' => 3,
'timezone' => 'UTC',
)): The given index is not in the valid type!