PHP Conference Japan 2024

ReflectionFunctionAbstract::getParameters

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getParameters取得參數

說明

public ReflectionFunctionAbstract::getParameters(): 陣列

ReflectionParameter 陣列的形式取得參數,順序與它們在原始碼中定義的順序相同。

參數

此函數沒有參數。

回傳值

參數,以 ReflectionParameter 物件形式返回。

參見

新增註釋

使用者貢獻的註釋 2 則註釋

dabidi at slupca dot pl
9 年前
這是我使用反射的私人框架的一部分。
此函數從主題方法中獲取參數列表,並從 $_REQUEST ($_GET、$_POST 和 $_COOKIE) 中放入相應的變數。

<?php
public static function fire_theme_method($class, $method)
{
$fire_args=array();

$reflection = new ReflectionMethod($class, $method);

foreach(
$reflection->getParameters() AS $arg)
{
if(
$_REQUEST[$arg->name])
$fire_args[$arg->name]=$_REQUEST[$arg->name];
else
$fire_args[$arg->name]=null;
}

return
call_user_func_array(array($class, $method), $fire_args);
}
?>
例如,如果我的主題方法只需要 id,而我們得到這個網址
http://example.com/my_class/my_method/?id=12&some_unwanted_var=123
some_unwanted_var 將被忽略

當然,在此背後我有 .htaccess、自動載入器和控制器
a dot lucassilvadeoliveira at gmail dot com
4 年前
我們可以使用此功能根據某些資料結構自動將參數傳遞給我們的函數。

注意:我使用的是 php 8.0 以上版本的功能,稱為「命名參數」。

<?php

$valuesToProcess
= [
'name' => 'Anderson Lucas Silva de Oliveira',
'age' => 21,
'hobbie' => 'Play games'
];

function
processUserData($name, $age, $job = "", $hobbie = "")
{
$msg = "Hello $name. You have $age years old";
if (!empty(
$job)) {
$msg .= ". Your job is $job";
}

if (!empty(
$hobbie)) {
$msg .= ". Your hobbie is $hobbie";
}

echo
$msg . ".";
}

$refFunction = new ReflectionFunction('processUserData');
$parameters = $refFunction->getParameters();

$validParameters = [];
foreach (
$parameters as $parameter) {
if (!
array_key_exists($parameter->getName(), $valuesToProcess) && !$parameter->isOptional()) {
throw new
DomainException('Cannot resolve the parameter' . $parameter->getName());
}

if(!
array_key_exists($parameter->getName(), $valuesToProcess)) {
continue;
}

$validParameters[$parameter->getName()] = $valuesToProcess[$parameter->getName()];
}

$refFunction->invoke(...$validParameters);
?>

執行結果:

Hello Anderson Lucas Silva de Oliveira. You have 21 years old. Your hobbie is Play games.
To Top