ReflectionFunction 类

(PHP 5, PHP 7, PHP 8)

简介

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

类摘要

ReflectionFunction extends ReflectionFunctionAbstract implements Reflector {
/* 常量 */
const integer IS_DEPRECATED = 262144 ;
/* 属性 */
public $name ;
/* 方法 */
public static export ( string $name , string $return = ? ) : string
public getClosure ( ) : Closure
public invoke ( mixed ...$args ) : mixed
public invokeArgs ( array $args ) : mixed
public isDisabled ( ) : bool
public __toString ( ) : string
/* 继承的方法 */
final private ReflectionFunctionAbstract::__clone ( ) : void
public ReflectionFunctionAbstract::getAttributes ( string $name = null , int $flags = 0 ) : array
abstract public ReflectionFunctionAbstract::__toString ( ) : void
}

属性

name

函数的名称。只读,并在尝试赋值的时候会抛出 ReflectionException

预定义常量

ReflectionFunction 修饰符

ReflectionFunction::IS_DEPRECATED

指示了不建议使用的函数。

Table of Contents

User Contributed Notes

a dot lucassilvadeoliveira at gmail dot com 28-Nov-2020 06:15
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.
Lorenz R.S. 12-Aug-2011 01:24
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 ]