Php reflection method invoke

The ReflectionMethod class

The ReflectionMethod class reports information about a method.

Class synopsis

Properties

Predefined Constants

ReflectionMethod Modifiers

Indicates that the method is static. Prior to PHP 7.4.0, the value was 1 .

ReflectionMethod::IS_PUBLIC

Indicates that the method is public. Prior to PHP 7.4.0, the value was 256 .

ReflectionMethod::IS_PROTECTED

Indicates that the method is protected. Prior to PHP 7.4.0, the value was 512 .

ReflectionMethod::IS_PRIVATE

Indicates that the method is private. Prior to PHP 7.4.0, the value was 1024 .

ReflectionMethod::IS_ABSTRACT

Indicates that the method is abstract. Prior to PHP 7.4.0, the value was 2 .

ReflectionMethod::IS_FINAL

Indicates that the method is final. Prior to PHP 7.4.0, the value was 4 .

Note:

The values of these constants may change between PHP versions. It is recommended to always use the constants and not rely on the values directly.

Changelog

Table of Contents

  • ReflectionMethod::__construct — Constructs a ReflectionMethod
  • ReflectionMethod::export — Export a reflection method
  • ReflectionMethod::getClosure — Returns a dynamically created closure for the method
  • ReflectionMethod::getDeclaringClass — Gets declaring class for the reflected method
  • ReflectionMethod::getModifiers — Gets the method modifiers
  • ReflectionMethod::getPrototype — Gets the method prototype (if there is one)
  • ReflectionMethod::hasPrototype — Returns whether a method has a prototype
  • ReflectionMethod::invoke — Invoke
  • ReflectionMethod::invokeArgs — Invoke args
  • ReflectionMethod::isAbstract — Checks if method is abstract
  • ReflectionMethod::isConstructor — Checks if method is a constructor
  • ReflectionMethod::isDestructor — Checks if method is a destructor
  • ReflectionMethod::isFinal — Checks if method is final
  • ReflectionMethod::isPrivate — Checks if method is private
  • ReflectionMethod::isProtected — Checks if method is protected
  • ReflectionMethod::isPublic — Checks if method is public
  • ReflectionMethod::setAccessible — Set method accessibility
  • ReflectionMethod::__toString — Returns the string representation of the Reflection method object

User Contributed Notes 3 notes

We can make a «Automatic dependenci injector» in classes when her constructors depends other classes (with type hint).

class Dependence1 function foo () echo «foo» ;
>
>

class Dependence2 function foo2 () echo «foo2» ;
>
>

final class myClass
private $dep1 ;
private $dep2 ;

public function __construct (
Dependence1 $dependence1 ,
Dependence2 $dependence2
)
$this -> dep1 = $dependence1 ;
$this -> dep2 = $dependence2 ;
>

Читайте также:  Обратная связь

// Automatic dependence injection (CLASSES)

$constructor = new ReflectionMethod ( myClass ::class, ‘__construct’ );
$parameters = $constructor -> getParameters ();

$dependences = [];
foreach ( $parameters as $parameter ) $dependenceClass = (string) $parameter -> getType ();
$dependences [] = new $dependenceClass ();
>

$instance = new myClass (. $dependences );
var_dump ( $instance );

object(myClass)#6 (2) [«dep1″:»myClass»:private]=>
object(Dependence1)#4 (0) >
[«dep2″:»myClass»:private]=>
object(Dependence2)#5 (0) >
>

Note that the public member $class contains the name of the class in which the method has been defined:

$method = new ReflectionMethod ( ‘B’ , ‘__construct’ );
echo $method -> class ; // prints ‘A’
?>

I have written a function which returns the value of a given DocComment tag.

header ( ‘Content-Type: text/plain’ );

class Example
<
/**
* This is my DocComment!
*
* @DocTag: prints Hello World!
*/
public function myMethod ()
<
echo ‘Hello World!’ ;
>
>

function getDocComment ( $str , $tag = » )
<
if (empty( $tag ))
<
return $str ;
>

$matches = array();
preg_match ( «/» . $tag . «:(.*)(\\r\\n|\\r|\\n)/U» , $str , $matches );

if (isset( $matches [ 1 ]))
<
return trim ( $matches [ 1 ]);
>

$method = new ReflectionMethod ( ‘Example’ , ‘myMethod’ );

// will return Hello World!
echo getDocComment ( $method -> getDocComment (), ‘@DocTag’ );

?>

Maybe you can add this functionality to the getDocComment methods of the reflection classes.

  • Reflection
    • Introduction
    • Installing/Configuring
    • Predefined Constants
    • Examples
    • Extending
    • Reflection
    • ReflectionClass
    • ReflectionClassConstant
    • ReflectionEnum
    • ReflectionEnumUnitCase
    • ReflectionEnumBackedCase
    • ReflectionZendExtension
    • ReflectionExtension
    • ReflectionFunction
    • ReflectionFunctionAbstract
    • ReflectionMethod
    • ReflectionNamedType
    • ReflectionObject
    • ReflectionParameter
    • ReflectionProperty
    • ReflectionType
    • ReflectionUnionType
    • ReflectionGenerator
    • ReflectionFiber
    • ReflectionIntersectionType
    • ReflectionReference
    • ReflectionAttribute
    • Reflector
    • ReflectionException

    Источник

    ReflectionMethod::invoke

    The object to invoke the method on. For static methods, pass null to this parameter.

    Zero or more parameters to be passed to the method. It accepts a variable number of parameters which are passed to the method.

    Return Values

    Returns the method result.

    Errors/Exceptions

    A ReflectionException if the object parameter does not contain an instance of the class that this method was declared in.

    A ReflectionException if the method invocation failed.

    Examples

    Example #1 ReflectionMethod::invoke() example

    public function sayHelloTo ( $name ) return ‘Hello ‘ . $name ;
    >

    $reflectionMethod = new ReflectionMethod ( ‘HelloWorld’ , ‘sayHelloTo’ );
    echo $reflectionMethod -> invoke (new HelloWorld (), ‘Mike’ );
    ?>

    The above example will output:

    Notes

    Note:

    ReflectionMethod::invoke() cannot be used when reference parameters are expected. ReflectionMethod::invokeArgs() has to be used instead (passing references in the argument list).

    See Also

    User Contributed Notes 3 notes

    Note: If you want to invoke protected or private methods, you’ll first have to make them accessible using the setAccessible() method (see http://php.net/reflectionmethod.setaccessible ).

    This method can be used to call a overwritten public method of a parent class on an child instance
    The following code will output «A»:

    class A
    public function foo ()
    return __CLASS__ ;
    >
    >

    class B extends A
    public function foo ()
    return __CLASS__ ;
    >
    >

    $reflection = new ReflectionObject ( $b );

    $parentReflection = $reflection -> getParentClass ();

    $parentFooReflection = $parentReflection -> getMethod ( ‘foo’ );

    $data = $parentFooReflection -> invoke ( $b );

    Источник

    ReflectionMethod::invokeArgs

    Invokes the reflected method and pass its arguments as array.

    Parameters

    The object to invoke the method on. In case of static methods, you can pass null to this parameter.

    The parameters to be passed to the function, as an array .

    Return Values

    Returns the method result.

    Errors/Exceptions

    A ReflectionException if the object parameter does not contain an instance of the class that this method was declared in.

    A ReflectionException if the method invocation failed.

    Changelog

    Version Description
    8.0.0 args keys will now be interpreted as parameter names, instead of being silently ignored.

    Examples

    Example #1 ReflectionMethod::invokeArgs() example

    public function sayHelloTo ( $name ) return ‘Hello ‘ . $name ;
    >

    $reflectionMethod = new ReflectionMethod ( ‘HelloWorld’ , ‘sayHelloTo’ );
    echo $reflectionMethod -> invokeArgs (new HelloWorld (), array( ‘Mike’ ));
    ?>

    The above example will output:

    Notes

    Note:

    If the function has arguments that need to be references, then they must be references in the passed argument list.

    See Also

    User Contributed Notes 4 notes

    We can do black magic, which is useful in templating block calls:

    $object -> __named ( ‘methodNameHere’ , array( ‘arg3’ => ‘three’ , ‘arg1’ => ‘one’ ));

    /**
    * Pass method arguments by name
    *
    * @param string $method
    * @param array $args
    * @return mixed
    */
    public function __named ( $method , array $args = array())
    <
    $reflection = new ReflectionMethod ( $this , $method );

    $pass = array();
    foreach( $reflection -> getParameters () as $param )
    <
    /* @var $param ReflectionParameter */
    if(isset( $args [ $param -> getName ()]))
    <
    $pass [] = $args [ $param -> getName ()];
    >
    else
    <
    $pass [] = $param -> getDefaultValue ();
    >
    >

    return $reflection -> invokeArgs ( $this , $pass );
    >
    ?>

    There is a simple workaround for the reference passing problem:
    Since the reflection api has to handle all parameters in a generic way it has no chance to guess if you wish to pass data per value or reference.

    But it seems that you can also decide to pass a reference from where you call the function or method (not just only by the ampersand prefix in its declaration).

    So just do the following; which worked for me:

    //.
    $method -> invoke ( $object , $inputValue , & $outputValue );
    ?>

    Since this will only be necessary with arrays and primitive data types it should be acceptable in most cases to know in advance if you need to pass per reference. But it is probably although necessary to keep the ampersand always in the declaration (because of the at least two layers between the actual function and your invoke call).

    If this is the expected behavior it will maybe make sense to mention it in the documentation for invoke and invokeArgs.

    If you need to call ReflectionMethod::invokeArgs() on a static function you can pass NULL in for the $object parameter.

    class myClass public static myStaticFunc ( $a , $b ) return $a + $b ;
    >
    >

    $ref = new ReflectionMethod ( ‘myClass’ , ‘myStaticFunc’ );
    echo $ref -> invokeArgs ( NULL , [ 12 , 7 ]);
    ?>

    produces the following output:

    Источник

    ReflectionFunction::invoke

    The passed in argument list. It accepts a variable number of arguments which are passed to the function much like call_user_func() is.

    Return Values

    Returns the result of the invoked function call.

    Examples

    Example #1 ReflectionFunction::invoke() example

    function title ( $title , $name )
    return sprintf ( «%s. %s\r\n» , $title , $name );
    >

    $function = new ReflectionFunction ( ‘title’ );

    echo $function -> invoke ( ‘Dr’ , ‘Phil’ );
    ?>

    The above example will output:

    Notes

    Note:

    ReflectionFunction::invoke() cannot be used when reference parameters are expected. ReflectionFunction::invokeArgs() has to be used instead (passing references in the argument list).

    See Also

    User Contributed Notes 1 note

    I know Reflections classes have a lot of power, but sometimes all we need is to store a annonymus function or even create a simple callback somewhere.

    so here it is, the Callback class:
    class Callback private $name = false ;

    public function Callback ( $obj , $call = false ) $name = array( $obj );
    if( $call ) $name [] = $call ;

    $this -> name = $name ;
    >
    public function invoke ( $params =array()) return call_user_func_array ( $this -> name , $params );
    >
    >
    ?>

    Usage:
    function sayName () return «goku» ;
    >

    $myVar = new Callback ( «sayName» );

    echo «Hi, I am » . $myVar -> invoke (). «!» ;

    //also works with methods: new Callback($obj,»method»);
    ?>

    Источник

Оцените статью