The ReflectionFunction class

(PHP 5, PHP 7, PHP 8)

Introduzione

The ReflectionFunction class reports information about a function.

Sommario della classe

class ReflectionFunction extends ReflectionFunctionAbstract {
/* Costanti */
public const int IS_DEPRECATED;
/* Proprietà ereditate */
public string $name;
/* Metodi */
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(
    since: '8.0',
    message: "as ReflectionFunction can no longer be constructed for disabled functions",
)]

public function isDisabled(): bool
public function __toString(): string
/* Metodi ereditati */
public function ReflectionFunctionAbstract::getAttributes(?string $name = null, int $flags = 0): array
abstract public function ReflectionFunctionAbstract::__toString(): void
}

Costanti predefinite

ReflectionFunction Modifiers

ReflectionFunction::IS_DEPRECATED int

Indicates deprecated functions.

Log delle modifiche

Versione Descrizione
8.4.0 The class constants are now typed.
8.0.0 ReflectionFunction::export() was removed.

Indice dei contenuti

add a note

User Contributed Notes 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()] =