PHP Conference Japan 2024

ReflectionFunction 類別

(PHP 5, PHP 7, PHP 8)

簡介

ReflectionFunction 類別會回報關於函式的資訊。

類別概要

class ReflectionFunction extends ReflectionFunctionAbstract {
/* 常數 */
public const int IS_DEPRECATED;
/* 繼承的屬性 */
公開 字串 $name;
/* 方法 */
公開 __construct(Closure|字串 $function)
公開 靜態 export(字串 $name, 字串 $return = ?): 字串
公開 invoke(混合 ...$args): 混合
公開 invokeArgs(陣列 $args): 混合
公開 __toString(): 字串
/* 繼承的方法 */
}

預定義常數

ReflectionFunction 修飾符

ReflectionFunction::IS_DEPRECATED 整數

表示已棄用的函式。

更新日誌

版本 說明
8.4.0 類別常數現在已鍵入。
8.0.0 ReflectionFunction::export() 已移除。

目錄

新增註釋

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

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('無法解析參數' . $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.
Lorenz R.S.
13 年前
以下是一個簡潔的 ReflectionFunction 使用範例,用於參數反射/內省(例如,自動產生 API 說明)。

<?php
$properties
= $reflector->getProperties();
$refFunc = new ReflectionFunction('preg_replace');
foreach(
$refFunc->getParameters() as $param ){
// 呼叫 ■ReflectionParameter::__toString
print $param;
}
?>

輸出結果:

參數 #0 [ <必要> $regex ]
參數 #1 [ <必要> $replace ]
參數 #2 [ <必要> $subject ]
參數 #3 [ <選用> $limit ]
參數 #4 [ <選用> &$count ]
To Top