請注意,公開成員 $class 包含定義 method 的類別名稱。
<?php
class A {public function __construct() {}}
class B extends A {}
$method = new ReflectionMethod('B', '__construct');
echo $method->class; // 顯示 'A'
?>
(PHP 5, PHP 7, PHP 8)
ReflectionMethod 類別回報關於方法的資訊。
方法名稱
類別名稱
ReflectionMethod::IS_STATIC
整數表示該方法為靜態方法。在 PHP 7.4.0 之前,其值為 1
。
ReflectionMethod::IS_PUBLIC
整數表示該方法為公開方法。在 PHP 7.4.0 之前,其值為 256
。
ReflectionMethod::IS_PROTECTED
整數表示該方法為保護方法。在 PHP 7.4.0 之前,其值為 512
。
ReflectionMethod::IS_PRIVATE
整數表示該方法為私有方法。在 PHP 7.4.0 之前,其值為 1024
。
ReflectionMethod::IS_ABSTRACT
整數表示該方法為抽象方法。在 PHP 7.4.0 之前,其值為 2
。
ReflectionMethod::IS_FINAL
整數表示該方法為最終方法。在 PHP 7.4.0 之前,其值為 4
。
注意事項:
這些常數的值可能會在不同 PHP 版本之間有所變更。建議始終使用常數,而不要直接依賴數值。
版本 | 說明 |
---|---|
8.4.0 | 類別常數現在已加入型別提示。 |
8.0.0 | ReflectionMethod::export() 已移除。 |
請注意,公開成員 $class 包含定義 method 的類別名稱。
<?php
class A {public function __construct() {}}
class B extends A {}
$method = new ReflectionMethod('B', '__construct');
echo $method->class; // 顯示 'A'
?>
當類別的建構子依賴其他類別(使用型別提示)時,我們可以在類別中建立「自動依賴注入器」。
<?php
類別 Dependence1 {
函式 foo() {
echo "foo";
}
}
類別 Dependence2 {
函式 foo2() {
echo "foo2";
}
}
最終類別 myClass
{
私有 $dep1;
私有 $dep2;
公開函式 __construct(
Dependence1 $dependence1,
Dependence2 $dependence2
)
{
$this->dep1 = $dependence1;
$this->dep2 = $dependence2;
}
}
// 自動依賴注入 (類別)
$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) {
}
}