PHP Conference Japan 2024

ReflectionFunctionAbstract::getNumberOfParameters

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

ReflectionFunctionAbstract::getNumberOfParameters取得參數數量

說明

public ReflectionFunctionAbstract::getNumberOfParameters(): int

取得函式定義的參數數量,包含選用和必填參數。

參數

此函式沒有參數。

回傳值

參數的數量。

參見

新增筆記

使用者貢獻的筆記 2 則筆記

Robert Pitt ( LitePHP )
14 年前
在開發新的 MVC 應用程式框架時,我使用這個方法來檢查在呼叫子方法之前需要多少個參數!

範例

<?php
$this
->method_args_count = $this->CReflection
->getMethod($Route->getMethod())
->
getNumberOfParameters();
//或許是 5 個,但如果網址是 /controller/method/single_param/,我們就只有 1 個
$this->params = $Route->getParams(); //在某些情況下為 0

if($this->method_args_count > count($this->params))
{
$this->difference = ($this->method_args_count - count($this->params));
for(
$i=0;$i<=$this->difference;$i++)
{
$this->params[] = false;
}
}

//使用正確數量的參數呼叫方法
// 但對於未傳遞的參數則設為 false!
call_user_func_array(array(new $this->obj,$Route->getMethod()),$this->params);
?>
8ctopus
4 年前
$reflection = new ReflectionFunction('implode');
echo $reflection->getNumberOfParameters();
To Top