(PHP 5, PHP 7, PHP 8)
Класс ReflectionMethod сообщает информацию о методах.
Имя метода
Имя класса
ReflectionMethod::IS_STATIC
int
Указывает на то, что это статический метод.
До PHP 7.4.0, значение было 1.
ReflectionMethod::IS_PUBLIC
int
Указывает на то, что это общедоступный метод.
До PHP 7.4.0, значение было 256.
ReflectionMethod::IS_PROTECTED
int
Указывает на то, что это защищённый метод.
До PHP 7.4.0, значение было 512.
ReflectionMethod::IS_PRIVATE
int
Указывает на то, что это закрытый метод.
До PHP 7.4.0, значение было 1024.
ReflectionMethod::IS_ABSTRACT
int
Указывает на то, что это абстрактный метод.
До PHP 7.4.0, значение было 2.
ReflectionMethod::IS_FINAL
int
Указывает на то, что это окончательный метод.
До PHP 7.4.0, значение было 4.
Замечание:
Значения этих констант могут изменяться от версии к версии PHP. Рекомендуется всегда использовать константы и не полагаться напрямую на значения.
| Версия | Описание |
|---|---|
| 8.4.0 | Константы класса теперь типизированы. |
| 8.0.0 | Метод ReflectionMethod::export() был удалён. |
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) {
}
}