(PHP 5, PHP 7, PHP 8)
The ReflectionMethod class reports information about a method.
Method name
Class name
ReflectionMethod::IS_STATIC
int
Indicates that the method is static.
Prior to PHP 7.4.0, the value was 1
.
ReflectionMethod::IS_PUBLIC
int
Indicates that the method is public.
Prior to PHP 7.4.0, the value was 256
.
ReflectionMethod::IS_PROTECTED
int
Indicates that the method is protected.
Prior to PHP 7.4.0, the value was 512
.
ReflectionMethod::IS_PRIVATE
int
Indicates that the method is private.
Prior to PHP 7.4.0, the value was 1024
.
ReflectionMethod::IS_ABSTRACT
int
Indicates that the method is abstract.
Prior to PHP 7.4.0, the value was 2
.
ReflectionMethod::IS_FINAL
int
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.
Version | Description |
---|---|
8.4.0 | The class constants are now typed. |
8.0.0 | ReflectionMethod::export() was removed. |
Note that the public member $class contains the name of the class in which the method has been defined:
<?php
class A {public function __construct() {}}
class B extends A {}
$method = new ReflectionMethod('B', '__construct');
echo $method->class; // prints 'A'
?>
We can make a "Automatic dependenci injector" in classes when her constructors depends other classes (with type hint).
<?php
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);
?>
Results in:
object(myClass)#6 (2) {
["dep1":"myClass":private]=>
object(Dependence1)#4 (0) {
}
["dep2":"myClass":private]=>
object(Dependence2)#5 (0) {
}
}