PHP 8.5.8 Released!

ReflectionFunction 类

(PHP 5, PHP 7, PHP 8)

简介

ReflectionFunction 类报告有关函数的信息。

类摘要

class ReflectionFunction extends ReflectionFunctionAbstract {
/* 常量 */
public const int IS_DEPRECATED ;
/* 继承的属性 */
public string $name ;
/* 方法 */
public function __construct (Closure |string $function)
public static function export (string $name, string $return = ?): string
public function getClosure (): Closure
public function invoke (mixed ...$args): mixed
public function invokeArgs (array $args): mixed
public function isAnonymous (): bool
#[\Deprecated]
public function isDisabled (): bool
public function __toString (): string
/* 继承的方法 */
public function ReflectionFunctionAbstract::getAttributes (? string $name = null , int $flags = 0): array
abstract public function ReflectionFunctionAbstract::__toString (): void
}

预定义常量

ReflectionFunction 修饰符

ReflectionFunction::IS_DEPRECATED int

表示弃用函数。

更新日志

版本 说明
8.4.0 所有类常量现已类型化。
8.0.0 已移除 ReflectionFunction::export()

目录

发现了问题?

了解如何改进此页面提交拉取请求报告一个错误
+添加备注

用户贡献的备注 2 notes

up
9
a dot lucassilvadeoliveira at gmail dot com
5 years ago
We can use this functionality to automatically pass arguments to our function based on some data structure.
NOTE: I am using a php 8.0> feature called "Nameds parameter"
<?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);
?>

Results in:
Hello Anderson Lucas Silva de Oliveira. You have 21 years old. Your hobbie is Play games.
up
-3
Lorenz R.S.
14 years ago
Here is a concise example of ReflectionFunction usage for Parameter Reflection / introspection (e.g. to automatically generate API descriptions)
<?php
$properties = $reflector->getProperties();
$refFunc = new ReflectionFunction('preg_replace');
foreach( $refFunc->getParameters() as $param ){
 //invokes しかくReflectionParameter::__toString
 print $param;
}
?>

prints:
Parameter #0 [ <required> $regex ]
Parameter #1 [ <required> $replace ]
Parameter #2 [ <required> $subject ]
Parameter #3 [ <optional> $limit ]
Parameter #4 [ <optional> &$count ]
+添加备注

AltStyle によって変換されたページ (->オリジナル) /